如何检查Swift中数组索引是否越界

7

我希望能够在数组索引超出范围时进行检查。数组元素都是字符串,因此我尝试了以下代码,但它并不起作用:

if questions[3] != nil {
}

有人可以告诉我如何检查吗?

1个回答

11

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

  1. 预期的索引不低于0
  2. 数组的 count 大于预期的索引

let intendedIndex: Int = 3

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

1
并不是特别针对Swift的,但显然是一个可行的解决方案。本来希望有一种Swift特定的方法或者什么的,但看来并没有这样的东西。 - Blue Bot
1
为了不跳转到其他链接:如果(questions.indices.contains(intendedIndex)) { ... } - Neph Muw

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接