<分区>
我希望能够检查我的数组索引何时超出范围。数组元素都是字符串,所以我尝试做这样的事情但它不起作用:
if questions[3] != nil {
}
有人可以告诉我如何检查吗?
<分区>
我希望能够检查我的数组索引何时超出范围。数组元素都是字符串,所以我尝试做这样的事情但它不起作用:
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]
}
关于arrays - 如何检查数组索引是否超出范围 SWIFT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30198809/