This question already has an answer here:
这个问题在这里已有答案:
- Swift Array - Check if an index exists 7 answers
Swift数组 - 检查索引是否存在7个答案
I want to be able to check when my array index goes out of range. The array elements are all strings, so I tried to do something like this but it doesn't work:
我希望能够检查我的数组索引何时超出范围。数组元素都是字符串,所以我尝试做这样的事情,但它不起作用:
if questions[3] != nil {
}
Can someone just show me how to check?
有人可以告诉我如何检查?
1 个解决方案
#1
Before indexing into the array, you need to check:
在索引到数组之前,您需要检查:
- The intended index is not below 0
- array's
count
is above the intended index
预期指数不低于0
数组的计数高于预期的索引
let intendedIndex: Int = 3
if (intendedIndex >= 0 && questions.count > intendedIndex) {
// This line will not throw index out of range:
let question3 = questions[intendedIndex]
}
#1
Before indexing into the array, you need to check:
在索引到数组之前,您需要检查:
- The intended index is not below 0
- array's
count
is above the intended index
预期指数不低于0
数组的计数高于预期的索引
let intendedIndex: Int = 3
if (intendedIndex >= 0 && questions.count > intendedIndex) {
// This line will not throw index out of range:
let question3 = questions[intendedIndex]
}