Skip to content

Instantly share code, notes, and snippets.

@sharplet
Created November 8, 2017 20:03
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sharplet/bc1871337f891ece083fd10618c1cca7 to your computer and use it in GitHub Desktop.
Save sharplet/bc1871337f891ece083fd10618c1cca7 to your computer and use it in GitHub Desktop.
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