Safe array subscription in Swift

An extension to access array elements with conditional binding

10 May 2020 · 2 min read

The possibility to use optionals in Swift allows us to write safe and expressive code. However, accessing elements from an array is not safe by default.

let shoppingList = ["apples", "raspberries"]
let item = shoppingList[2]

Accessing an element this way will crash the app if the element isn’t there. By adding the following extension to our code base, we have the possibility to access it in a safe way.

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

We know can access the item with conditional binding:

if let item = shoppingList[safe: 2] {
// use item
}