Last active
March 24, 2017 17:20
-
-
Save erica/9a3c80a2d8940460fbd030de8a30c2c9 to your computer and use it in GitHub Desktop.
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
extension Collection where | |
Indices.Iterator.Element: Equatable, | |
Index == Self.Indices.Iterator.Element | |
{ | |
/// Returns optional value for safely indexed value | |
/// and nil if index is out of bounds | |
public subscript(safe index: Self.Index) -> Self.Iterator.Element? { | |
guard indices.contains(index) else { return nil } | |
return self[index] | |
} | |
/// Returns objects safely collected at existing desired indices. | |
public func objects(collectedAt desiredIndices: Self.Index...) -> [Self.Iterator.Element] { | |
return desiredIndices.flatMap({ self[safe: $0] }) | |
} | |
/// Returns objects safely found at existing desired indices. | |
public func objects(safelyAt desiredIndices: Self.Index...) -> [Self.Iterator.Element?] { | |
return desiredIndices.map({ self[safe: $0] }) | |
} | |
} | |
extension Collection { | |
/// Returns objects found at existing desired indices. | |
/// No safety guarantees | |
public func objects(at desiredIndices: Self.Index...) -> [Self.Iterator.Element] { | |
return desiredIndices.map({ self[$0] }) | |
} | |
} | |
extension Collection { | |
/// Returns objects found at desired subscript indices. | |
/// No safety guarantees | |
subscript(_ idx1: Self.Index, _ idx2: Self.Index, _ rest: Self.Index...) -> [Self.Iterator.Element] { | |
return [self[idx1], self[idx2]] + rest.map({ self[$0] }) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment