Skip to content

Instantly share code, notes, and snippets.

@jaderfeijo
Last active June 19, 2018 10:14
Show Gist options
  • Save jaderfeijo/d7bf52e9c079497dc4653d0ce4f4b1b0 to your computer and use it in GitHub Desktop.
Save jaderfeijo/d7bf52e9c079497dc4653d0ce4f4b1b0 to your computer and use it in GitHub Desktop.
Safe element retrieval for Swift collections
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