Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Getting a sequence of lines from a Swift string
import Foundation
let text = """
Hello
World
"""
extension String {
var lines: AnySequence<Substring> {
let string = self
return AnySequence { () -> AnyIterator<Substring> in
var offset = string.startIndex
return AnyIterator {
let searchRange = offset..<string.endIndex
guard !searchRange.isEmpty else { return nil }
var substring: Substring?
string.enumerateSubstrings(in: searchRange, options: [.byLines, .substringNotRequired]) { _, line, enclosing, stop in
substring = string[line]
offset = enclosing.upperBound
stop = true
}
return substring
}
}
}
}
for line in text.lines {
print(line)
}
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.