Skip to content

Instantly share code, notes, and snippets.

@yucelokan
Last active October 19, 2022 13:22
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 yucelokan/2d40dc7f1c0fdf2a6d1623776c30388e to your computer and use it in GitHub Desktop.
Save yucelokan/2d40dc7f1c0fdf2a6d1623776c30388e to your computer and use it in GitHub Desktop.
An extension to access safely to items in an array.
// An extension to access safely to items in an array.
// usage:
// let anArray: [Item] = [......]
// let item = anArray[safe: 5]
public extension Collection {
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