Skip to content

Instantly share code, notes, and snippets.

@erica
Last active March 24, 2017 17:20
Show Gist options
  • Save erica/9a3c80a2d8940460fbd030de8a30c2c9 to your computer and use it in GitHub Desktop.
Save erica/9a3c80a2d8940460fbd030de8a30c2c9 to your computer and use it in GitHub Desktop.
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