Split a string with multiple lines into an array in Swift
To convert a given string with multiple lines into an array of lines in Swift, split the string by new line character using components() method of String class instance.
For example, if you would like to split a given string str by new line character, and get the lines in an array, use the following syntax.
str.components(separatedBy: "\n")
The above method returns the lines of string in an array.
Examples
1. Get the lines in a given string as an array
In this example, we take a string value in str, where the string is contains multiple lines, where the lines are separated by new line character. We shall split this string, and get the lines in an array linesArray. Each element in the resulting array is a line (string) from the original string.
main.swift
import Foundation
let str = "Hello World!\nApple is red.\nBanana is good."
let linesArray = str.components(separatedBy: "\n")
print(linesArray)
Output
Conclusion
In this Swift Tutorial, we have seen how to split a given multiline string into a string array of individual lines, with examples.