Skip to content

Instantly share code, notes, and snippets.

@qmchenry
Created July 11, 2016 18:53
Show Gist options
  • Save qmchenry/ab382850603baa3e9c447da8406e784c to your computer and use it in GitHub Desktop.
Save qmchenry/ab382850603baa3e9c447da8406e784c to your computer and use it in GitHub Desktop.
Swift subscript tricks
// 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