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!
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
Want to read more?
Here are some other articles you may enjoy.