Skip to main content

Safely index items within a collection

Updated:

We can make some great things with extensions in Swift, as well as subscript functions. This one allows us to safely access collection elements by index, getting back an optional instead of errors being thrown!

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

let numbers = [1, 2, 3, 4]
numbers[safe: 3] // 4
numbers[safe: 10] // nil, no error

I hope the article was useful. If you have any feedback or questions please feel free to reach out.

Thanks for reading!

Like what you read? Please share the article.

Avatar of Andrew Lord

WRITTEN BY

Andrew Lord

A software developer and tech leader from the UK. Writing articles that focus on all aspects of Android and iOS development using Kotlin and Swift.

Want to read more?

Here are some other articles you may enjoy.