Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
De-C++ified Rerverse
struct MyReversed<Base: BidirectionalCollection> {
let base: Base
}
extension MyReversed: Collection {
public enum Index: Comparable {
case element(Base.Index)
case end
public static func < (lhs: Index, rhs: Index) -> Bool {
switch (lhs,rhs) {
case let (.element(i),.element(j)):
return j < i
case (.end,.end), (.element,.end):
return true
case (.end,.element):
return false
}
}
public var baseIndex: Base.Index {
guard case let .element(i) = self
else { fatalError("Can't get equivalent of endIndex") }
return i
}
}
public var startIndex: Index { return .element(base.index(before: base.endIndex)) }
public var endIndex: Index { return .end }
public func index(after: Index) -> Index {
switch after {
case .end:
fatalError("Can't advance beyond endIndex")
case let .element(i) where i == base.startIndex:
return .end
case let .element(i):
return .element(base.index(before: i))
}
}
public typealias Element = Base.Element
public subscript(i: Index) -> Element {
return base[i.baseIndex]
}
}
extension BidirectionalCollection {
func myReversed() -> MyReversed<Self> {
return MyReversed(base: self)
}
}
let s = "find the last space"
let i = s.myReversed().index(of: " ")!
print("-->" + s[..<i.baseIndex] + "<--")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.