我希望能够在数组索引超出范围时进行检查。数组元素都是字符串,因此我尝试了以下代码,但它并不起作用:
if questions[3] != nil {
}
有人可以告诉我如何检查吗?
索引数组之前,您需要检查:
count
大于预期的索引let intendedIndex: Int = 3
if (intendedIndex >= 0 && questions.count > intendedIndex) {
// This line will not throw index out of range:
let question3 = questions[intendedIndex]
}