Created
July 11, 2016 18:53
-
-
Save qmchenry/ab382850603baa3e9c447da8406e784c to your computer and use it in GitHub Desktop.
Swift subscript tricks
This file contains hidden or 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
// http://stackoverflow.com/questions/25329186/safe-bounds-checked-array-lookup-in-swift-through-optional-bindings/30593673#30593673 | |
extension CollectionType { | |
/// Returns the element at the specified index iff it is within bounds, otherwise nil. | |
subscript (safe index: Index) -> Generator.Element? { | |
return indices.contains(index) ? self[index] : nil | |
} | |
} | |
// Usage: | |
if let element = array[safe: 17] { } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment