Skip to content

Instantly share code, notes, and snippets.

@blainerothrock
Created September 6, 2018 15:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blainerothrock/856a49d5ca8eb10f7ea017e06697513d to your computer and use it in GitHub Desktop.
Save blainerothrock/856a49d5ca8eb10f7ea017e06697513d to your computer and use it in GitHub Desktop.
Swift Safe Array Lookup
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