Swift 5.2 or later
You can split your String
using the new Character
property isNewline
:
let sentence = "Line 1
Line 2
Line 3
"
let lines = sentence.split(whereSeparator: .isNewline)
print(lines) // "["Line 1", "Line 2", "Line 3"]
"
You can also extend StringProtocol and create a lines instance property to break up the string lines into subsequences:
extension StringProtocol {
var lines: [SubSequence] { split(whereSeparator: .isNewline) }
}
let sentence = "Line 1
Line 2
Line 3
"
for line in sentence.lines {
print(line)
}
let lines = sentence.lines // ["Line 1", "Line 2", "Line 3"]
Original Answer
You can use String method enumerateLines:
Enumerates all the lines in a string.
Swift 3 or later
let sentence = "Line 1
Line 2
Line 3
"
var lines: [String] = []
sentence.enumerateLines { line, _ in
lines.append(line)
}
print(lines) // "["Line 1", "Line 2", "Line 3"]
"
extension String {
var lines: [String] {
var result: [String] = []
enumerateLines { line, _ in result.append(line) }
return result
}
}
let sentence2 = "Line 4
Line 5
Line 6
"
let sentence2Lines = sentence2.lines
print(sentence2Lines) // "["Line 4", "Line 5", "Line 6"]
"
let sentence3 = "Line 7
Line 8
Line 9
"
let sentence3Lines = sentence3.lines
print(sentence3Lines) // "["Line 7", "Line 8", "Line 9"]
"
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…