If I have an array in Swift, and try to access an index that is out of bounds, there is an unsurprising runtime error:
var str = ["Apple", "Banana", "Coconut"]
str[0] // "Apple"
str[3] // EXC_BAD_INSTRUCTION
However, I would have thought with all the optional chaining and safety that Swift brings, it would be trivial to do something like:
let theIndex = 3
if let nonexistent = str[theIndex] { // Bounds check + Lookup
print(nonexistent)
...do other things with nonexistent...
}
Instead of:
let theIndex = 3
if (theIndex < str.count) { // Bounds check
let nonexistent = str[theIndex] // Lookup
print(nonexistent)
...do other things with nonexistent...
}
But this is not the case - I have to use the ol' if statement to check and ensure the index is less than str.count.
I tried adding my own subscript() implementation, but I'm not sure how to pass the call to the original implementation, or to access the items (index-based) without using subscript notation:
extension Array {
subscript(var index: Int) -> AnyObject? {
if index >= self.count {
NSLog("Womp!")
return nil
}
return ... // What?
}
}
indices.containswhich is O(n) –thus, terribly inefficient for arrays, and 2) disregard the case where you are actually storing nil objects. - Janoindices.contains(O(n)) and @zubko's bound checking withreturn index >= startIndex && index < endIndex(O(1)). On an iPhone 11, the O(1) solution ran 15x faster than the O(n) solution but they both completed within 1/10 of a millisecond. So yes, the accepted answer is less efficient but the difference is not noticeable. If it's a major concern, I recommend adding anArrayextension with the same method signature that uses bound checking, and keeping theCollectionextension that usescontains. - Nathan Dudley