Skip to content

Instantly share code, notes, and snippets.

@josipbernat
Created November 4, 2020 11:46
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 josipbernat/1076de3b04806c7549a098818788b342 to your computer and use it in GitHub Desktop.
Save josipbernat/1076de3b04806c7549a098818788b342 to your computer and use it in GitHub Desktop.
Safe array access in swift let's you access index out of bounds without app crash
extension Collection {
/// Returns the element at the specified index if it is within bounds, otherwise nil.
subscript (safe index: Index) -> Element? {
return indices.contains(index) ? self[index] : nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment