Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent a 'Array index out of range' error?

Tags:

swift

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?

like image 243
webmagnets Avatar asked Mar 17 '15 03:03

webmagnets


1 Answers

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:

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
}
like image 131
GoZoner Avatar answered Sep 30 '22 20:09

GoZoner