Skip to content

Instantly share code, notes, and snippets.

@mminer
Last active October 18, 2017 04:37
Show Gist options
  • Save mminer/a48ef392f6532bd132dee856f4e3732a to your computer and use it in GitHub Desktop.
Save mminer/a48ef392f6532bd132dee856f4e3732a to your computer and use it in GitHub Desktop.
Collections extension for avoiding out-of-bounds exceptions.
extension Collection {
/// Returns the element at the specified index if it is within bounds, or nil if it's outside.
subscript(safe index: Index) -> Iterator.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