Safe (bounds-checked) array lookup in Swift, through optional bindings?

Alex’s answer has good advice and solution for the question, however, I’ve happened to stumble on a nicer way of implementing this functionality:

Swift 3.2 and newer

extension Collection {

    /// Returns the element at the specified index if it is within bounds, otherwise nil.
    subscript (safe index: Index) -> Element? {
        return indices.contains(index) ? self[index] : nil
    }
}

Swift 3.0 and 3.1

extension Collection where Indices.Iterator.Element == Index {

    /// Returns the element at the specified index if it is within bounds, otherwise nil.
    subscript (safe index: Index) -> Generator.Element? {
        return indices.contains(index) ? self[index] : nil
    }
}

Credit to Hamish for coming up with the solution for Swift 3.


Example

let array = [1, 2, 3]

for index in -20...20 {
    if let item = array[safe: index] {
        print(item)
    }
}

Leave a Comment