Swift Language Arrays Accessing indices safely


Example

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)
}