Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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