Skip to content

Instantly share code, notes, and snippets.

@lucascaton
Last active February 22, 2016 09:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lucascaton/47d89d9eee33d6fdde27 to your computer and use it in GitHub Desktop.
Save lucascaton/47d89d9eee33d6fdde27 to your computer and use it in GitHub Desktop.
By using functions like the following, it prevents app from crashing if you pass the wrong index (tip from @CassiusPacheco)
public extension Array {
    public subscript(safe index: Int) -> Element? {
        return self.indices ~= index ? self[index] : nil
    }
}
// ...
let optionalResult = array[safe: 1] // returns nil instead of crashing
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment