Skip to content

Instantly share code, notes, and snippets.

@Moximillian
Last active June 11, 2018 19:49
Show Gist options
  • Save Moximillian/b7643abc7d460e1673981d3f41bb9b40 to your computer and use it in GitHub Desktop.
Save Moximillian/b7643abc7d460e1673981d3f41bb9b40 to your computer and use it in GitHub Desktop.
/* Minimalist implementation of ReversedCollectionProtocol */
public protocol ReversedCollectionProtocol: BidirectionalCollection {
associatedtype Base: BidirectionalCollection
var _base: Base { get }
}
extension ReversedCollection: ReversedCollectionProtocol {}
extension LazyCollectionProtocol
where Self: BidirectionalCollection, Elements: ReversedCollectionProtocol {
/// Reversing a lazy reversed collection returns a lazy representation of the original collection.
public func reversed() -> LazyCollection<Elements.Base> {
return elements._base.lazy
}
}
// as an alternative, reversed() optimization for lazy collections using
// parametrized extensions, which not available in Swift 4.2 or older
// see: https://github.com/apple/swift/blob/master/docs/GenericsManifesto.md#parameterized-extensions
extension<T: BidirectionalCollection> LazyCollectionProtocol
where Self: BidirectionalCollection, Elements == ReversedCollection<T> {
/// Reversing a lazy reversed collection returns a lazy representation of the original collection.
public func reversed() -> LazyCollection<T> {
return elements._base.lazy
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment