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

时间:2022-10-05 16:41:06

Is there a way, similar to using if let and/or optionals, to test whether you are about to index an empty buffer in Swift?

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

1 个解决方案

#1


15  

Define your own:

定义你自己的:

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

The ref() function returns an optional, so it can be nil, and you can use the if let syntax to access the returned value from ref() when it exists. You would use this as such:

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
}

#1


15  

Define your own:

定义你自己的:

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

The ref() function returns an optional, so it can be nil, and you can use the if let syntax to access the returned value from ref() when it exists. You would use this as such:

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
}