Prevent “Array index out of range” Error in Swift

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]

 

Join the Conversation

2 Comments

Leave a comment

Leave a Reply to mdavison Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.