Skip to content

Instantly share code, notes, and snippets.

@T1T4N
Created August 8, 2017 09:29
Show Gist options
  • Save T1T4N/f3dd3c4a6552f10de0f69730c9eeb281 to your computer and use it in GitHub Desktop.
Save T1T4N/f3dd3c4a6552f10de0f69730c9eeb281 to your computer and use it in GitHub Desktop.
Safe collection indexing that returns an optional if index out of bounds
extension Collection {
/// Returns the element at the specified index iff it is within bounds, otherwise nil.
subscript (safe index: Index) -> Element? {
return indices.contains(index) ? self[index] : nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment