如何防止'数组索引超出范围'错误?

web*_*ets 13 swift

是否有一种方法,类似于使用if let和/或选项,来测试你是否要在Swift中索引一个空缓冲区?

GoZ*_*ner 15

定义你自己的:

extension Array {
  func ref (i:Int) -> T? {
    return 0 <= i && i < count ? self[i] : nil
  }
}
Run Code Online (Sandbox Code Playgroud)

ref()函数返回一个可选项,因此它可以是nil,并且您可以使用该if let语法从ref()存在时访问返回的值.您可以这样使用:

var myA = [10,20,30]
if let val = myA.ref(index) {
  // Use 'val' if index is < 3
}
else {
  // Do this if the index is too high
}
Run Code Online (Sandbox Code Playgroud)