13

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?

2
  • I don't know what it means. That is an error I get when I try to access an array index that doesn't exist yet; too high. The array might have 10 elements, but the app tries to access the 11th. Commented Mar 17, 2015 at 3:39
  • So it's an array, check the bounds of an array using the count property (array.count) GoZoner gives an example in his answer. Commented Mar 17, 2015 at 5:08

1 Answer 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:

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

I don't understand this very well. Can you show me how to use it and maybe what it is doing?
I think ref needs a better name. But I couldn't think one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.