You can iterate (loop) over lines in a string using enumerateLines(invoking:) method which calls a given closure on each line of the string:
var str = "Foundation\nSwift\nString"
str.enumerateLines { (line, _) in
print(line)
}
The above code prints out each line separately.
Get an array containing all of the lines in a string
In order to split a string into an array of individual lines, you can use the components(separatedBy:) method:
var str = "Foundation\nSwift\nString"
var lines = str.components(separatedBy: "\n")
The lines variable now contains the following array:
["Foundation", "Swift", "String”]
Related tutorials:
- How to split a string into an array of strings in Swift
- How to iterate over characters in a string in Swift
- Get a character from string using its index in Swift