如何检查数组索引是否超出范围SWIFT [重复]

时间:2022-07-01 21:13:21

This question already has an answer here:

这个问题在这里已有答案:

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:

在索引到数组之前,您需要检查:

  1. The intended index is not below 0
  2. 预期指数不低于0

  3. array's count is above the intended index
  4. 数组的计数高于预期的索引


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:

在索引到数组之前,您需要检查:

  1. The intended index is not below 0
  2. 预期指数不低于0

  3. array's count is above the intended index
  4. 数组的计数高于预期的索引


let intendedIndex: Int = 3

if (intendedIndex >= 0 && questions.count > intendedIndex) {
    // This line will not throw index out of range:
    let question3 = questions[intendedIndex]
}