Skip to content

Instantly share code, notes, and snippets.

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 zs40x/a87e896db7b8381b1e45d378a6d787a4 to your computer and use it in GitHub Desktop.
Save zs40x/a87e896db7b8381b1e45d378a6d787a4 to your computer and use it in GitHub Desktop.
extension Collection where Indices.Iterator.Element == Index {
subscript (safe index: Index) -> Generator.Element? {
return indices.contains(index) ? self[index] : nil
}
}
class ArrayLookup {
private let array = ["Hello", "World"]
func valueForIndex(_ index: Int) -> String {
guard let value = array[safe: index] else {
return "n/a"
}
return value
}
}
let arrayLookup = ArrayLookup()
arrayLookup.valueForIndex(0)
arrayLookup.valueForIndex(1)
arrayLookup.valueForIndex(2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment