If you don’t know if the array index you are calling exists, here is a nice way to just return nil
instead of an error. I grabbed this from StackOverflow but unfortunately lost the link. I am putting it here because I use it once in a while and get tired of searching for it.
extension Array { subscript (safe index: Int) -> Element? { return indices ~= index ? self[index] : nil } }
Use it like this:
array.item[safe: 1]
In other words: `indices ~= index` means `indices.contains(index)`
Thanks to a reader who found it for me, it looks like this is the SO post I got it from. It’s updated for Swift 4 too.
https://stackoverflow.com/questions/37222811/how-do-i-catch-index-out-of-range-in-swift
Sandel managed to copy your code 🙂
https://www.hackingwithswift.com/example-code/language/how-to-make-array-access-safer-using-a-custom-subscript