How to iterate over lines in a string in Swift

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

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: