Created
June 6, 2017 00:17
-
-
Save airspeedswift/e7e02943c4c4463da919a9a825f33def to your computer and use it in GitHub Desktop.
Lazy split: Swift 3 vs Swift 4
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
// Swift 4.0 (and 3.2 as well!) | |
struct LazySplit<Base: Collection>: Collection | |
where Base.Element: Equatable, | |
Base.SubSequence: Collection | |
{ | |
struct Index: Comparable { | |
let start, end: Base.Index | |
static func ==(lhs: Index, rhs: Index) -> Bool { return lhs.start == rhs.start } | |
static func < (lhs: Index, rhs: Index) -> Bool { return lhs.start < rhs.start } | |
} | |
func findEnd(_ i: Base.Index) -> Base.Index { | |
return _base[i...].index(of: _separator) ?? _base.endIndex | |
} | |
let _base: Base | |
let _separator: Base.Element | |
var startIndex: Index { return Index(start: _base.startIndex, end: findEnd(_base.startIndex)) } | |
var endIndex: Index { return Index(start: _base.endIndex, end: _base.endIndex) } | |
func index(after i : Index) -> Index { | |
if i.end == _base.endIndex { | |
return endIndex | |
} | |
else { | |
let nextStart = _base.index(after: i.end) | |
let nextEnd = findEnd(nextStart) | |
return Index(start: nextStart, end: nextEnd) | |
} | |
} | |
subscript(i: Index) -> Base.SubSequence { | |
return _base[i.start..<i.end] | |
} | |
} | |
extension LazyCollectionProtocol | |
where Elements.Element: Equatable, | |
Elements.SubSequence: Collection | |
{ | |
func split(separator: Elements.Element) -> LazySplit<Elements> { | |
return LazySplit(_base: self.elements, _separator: separator) | |
} | |
} | |
"1,2,3".lazy.split(separator: ",").forEach { print($0) } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment