Ondrej Rafaj
Ondrej Rafaj

Reputation: 4417

Split lines without omitting empty lines in Swift

How can I split lines in Swift (4+) without omitting the empty rows?

Both "1\n2\n\n3".split { $0.isNewline } and "1\n2\n\n3".split(separator: "\n") give me only three items while I need 4 with the third one beiing empty

Upvotes: 6

Views: 742

Answers (2)

Rem-D
Rem-D

Reputation: 675

You could try:

"1\n2\n\n3".components(separatedBy: "\n")

Or more concise and readable, as suggested by Leo Dabus:

"1\n2\n\n3".components(separatedBy: .newlines)

These both result in: ["1", "2", "", "3"]

Upvotes: 5

user28434'mstep
user28434'mstep

Reputation: 6600

split has omittingEmptySubsequences parameter just for that.

By default it's true. So just set it to false:

"1\n2\n\n3".split(omittingEmptySubsequences: false) { $0.isNewline }

Upvotes: 7

Related Questions