Created
July 8, 2020 07:55
-
-
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.
This file contains 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 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