Last active
June 19, 2018 10:14
-
-
Save jaderfeijo/d7bf52e9c079497dc4653d0ce4f4b1b0 to your computer and use it in GitHub Desktop.
Safe element retrieval for Swift collections
This file contains hidden or 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
infix operator ~>: DefaultPrecedence | |
extension Collection { | |
/// Returns the element at the specified index if it is within bounds, otherwise nil. | |
/// | |
/// This extension allows you to write code as follows: | |
/// - Example: | |
/// ``` | |
/// if let element = array ~> index { | |
/// // do something with element | |
/// } else { | |
/// // handle case where the index is out of the bounds | |
/// // of the array | |
/// } | |
/// ``` | |
/// | |
/// - Parameters: | |
/// - collection: The collection where the item to be retreived is. | |
/// - index: The index of the item to be retrieved | |
/// | |
/// - Returns: Returns the `Element` at the specified `index` or `nil` if the specified | |
/// `index` is out of bounds. | |
static func ~>(collection: Self, index: Index) -> Element? { | |
return collection.indices.contains(index) ? collection[index] : nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment