Created
November 8, 2017 20:03
-
-
Save sharplet/bc1871337f891ece083fd10618c1cca7 to your computer and use it in GitHub Desktop.
Getting a sequence of lines from a Swift string
This file contains 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
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