Skip to content

Instantly share code, notes, and snippets.

@sindresorhus
Created January 19, 2022 13:18
Show Gist options
  • Save sindresorhus/a4706e81fbac24b5380a0d6d6bfb584e to your computer and use it in GitHub Desktop.
Save sindresorhus/a4706e81fbac24b5380a0d6d6bfb584e to your computer and use it in GitHub Desktop.
extension Collection {
/**
Returns the element at the given index if any, otherwise `nil`.
```
guard let element = array[position] else {
return
}
print(element)
```
*/
subscript(safe index: Index) -> Element? {
indices.contains(index) ? self[index] : nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment