Swift extension 3 and 4:
extension Collection { subscript(optional i: Index) -> Iterator.Element? { return self.indices.contains(i) ? self[i] : nil } }
Using this, you return an optional value when you add a keyword optional to your index, which means that your program does not crash, even if the index is out of range. In your example:
let arr = ["foo", "bar"] let str1 = arr[optional: 1] // --> str1 is now Optional("bar") if let str2 = arr[optional: 2] { print(str2) // --> this still wouldn't run } else { print("No string found at that index") // --> this would be printed }
Benno Kress May 01 '17 at 1:41 pm 2017-05-01 13:41
source share