Skip to content

Instantly share code, notes, and snippets.

@kayoslab
Created July 8, 2020 07:55
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 kayoslab/f14f71e15ba70e0a871a983599b09431 to your computer and use it in GitHub Desktop.
Save kayoslab/f14f71e15ba70e0a871a983599b09431 to your computer and use it in GitHub Desktop.
A safe way to subscribe collection items. This should put a definite end to index-out-of-bounds errors.
import Foundation
extension Collection {
/// Safe subscription for collection elements.
///
/// - Parameter safe: The index of which the element should be returned.
/// - Returns: The element at the given index if present, 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