Skip to content

Instantly share code, notes, and snippets.

@natecook1000
Created October 23, 2017 17:34
Show Gist options
  • Select an option

  • Save natecook1000/7d6ebbd3c6cc7fdf73e57678ca2ed91c to your computer and use it in GitHub Desktop.

Select an option

Save natecook1000/7d6ebbd3c6cc7fdf73e57678ca2ed91c to your computer and use it in GitHub Desktop.
// This makes it possible to use an `Indices` in a collection's subscript.
// Since indices are generally their own slice type, this makes using
// the subsequence of an indices useful...
extension DefaultRandomAccessIndices : RangeExpression {
public func relative<C>(to collection: C) -> Range<Element>
where C : _Indexable, Element == C.Index
{
if isEmpty {
return collection.startIndex ..< collection.startIndex
}
return first! ..< collection.index(after: last!)
}
}
let a = [1, 2, 3, 1, 2, 3, 1, 2, 3]
let rev = a.reversed()
let revIndices = (rev.indices.dropFirst(2) as DefaultRandomAccessIndices).dropLast(2)
Array(rev[revIndices].reversed()) // [3, 1, 2, 3, 1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment