Skip to main content

Articles, snippets and thoughts about code from Andrew Lord.

Safely index items within a collection

Published on · Updated on
1 minute read

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 to me on Twitter.

Thanks for reading and happy coding!

Like what you read? Please share the article.

Avatar of Andrew Lord

Hi, I hope you enjoyed the article. I am Andrew - a builder of apps and developer tools. Articles on the blog focus on all aspects of Android and iOS development using Kotlin and Swift.

Subscribe via RSS