Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Lazy split: Swift 3 vs Swift 4
// 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
You can’t perform that action at this time.