Accessing indices safely

suggest change

By adding the following extension to array indices can be accessed without knowing if the index is inside bounds.

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