Skip to content

Instantly share code, notes, and snippets.

@boraseoksoon
Created May 9, 2023 02:23
Show Gist options
  • Save boraseoksoon/3bbebd4957aac3e0875a40ecc3da1057 to your computer and use it in GitHub Desktop.
Save boraseoksoon/3bbebd4957aac3e0875a40ecc3da1057 to your computer and use it in GitHub Desktop.
Swift safe access to index of collection
extension Collection where Indices.Iterator.Element == Index {
subscript (safe index: Index) -> Iterator.Element? {
return indices.contains(index) ? self[index] : nil
}
}
// let array = [0,1,2,3,4,5]
// array[safe: 10]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment