Created
June 11, 2017 06:53
-
-
Save zs40x/a87e896db7b8381b1e45d378a6d787a4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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