Created
September 6, 2018 15:20
-
-
Save blainerothrock/856a49d5ca8eb10f7ea017e06697513d to your computer and use it in GitHub Desktop.
Swift Safe Array Lookup
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
import Foundation | |
extension Array { | |
subscript (lookup index: Index) -> Element? { | |
return indices.contains(index) ? self[index] : nil | |
} | |
} | |
let array = [1,2,3,4,5] | |
array[lookup: 7] // nil | |
array[lookup: 1] // 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment