Arrays are a common data structure in Swift:
let l = ["alice", "bob", "charlie"]
dump(l[2])
But array subscripting is unchecked, so this will crash at runtime:
dump(l[3])
Here's an extension to add a checked subscripting operator:
extension Array {
subscript(checked index: UInt) -> Element? {
if index < count {
return self[Index(index)]
} else {
return nil
}
}
}
So you can do:
dump(l[checked: 2])
dump(l[checked: 3])
Since it returns an Optional
, you can do:
if let element = l[checked: 2] {
NSLog("Value: \(element)")
}
Note that the argument is UInt
instead of Int
or Index
so the compiler can check when you pass in a negative index like this:
dump(l[checked: -1])
Your feedback is valuable: Do you want more nuggets like this? Yes or No
.
.