Safe Collection Subscript


Safe subscript protects the collection from out of bounds error by using optionals.

Instead of manually checking if index is is valid, extend Collection creating a subscript that returns an optional element.

let array = ["John", "Mike"] let name = array[1] // "Mike" let name = array[2] // Crash
With the extension:
let array = ["John", "Mike"] let name = array[safe: 1] // "Mike" let name = array[safe: 2] // nil

The extension:


extension Collection { subscript(safe index: Index) -> Element? { return indices.contains(index) ? self[index] : nil } }