Accessing indices safely

suggest change

The following extension lets you access an array index without knowing whether that index is in bounds. The subscript returns nil when it is not.

extension Array {
    subscript (safe index: Int) -> Element? {
        return indices ~= index ? self[index] : nil
    }
}

Example:

if let thirdValue = array[safe: 2] {
    print(thirdValue)
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents