Email or username:

Password:

Forgot your password?
Rob Napier

For those of you who don't have your own personal @Catfish_Man to answer your questions (you really should; it's quite the time saver, but get your own):

Interesting fact I learned today. In Swift, "\r\n" is one Character because that's what Unicode requires. unicode.org/reports/tr29/#GB3

So str.split("\n") may not do what you expect if \r\n is present. \r\n is one Character, which is not equal to \n, so it won't split at all. (I expected it to split, and leave the \r, but Unicode says no).

9 comments
Miguel Arroz

@cocoaphony @Catfish_Man Oh yeah, that's a great consequence of how Swift handles strings. No need to fiddle with new-line sequences, as they are just characters. However, to split, always use Character.isNewLine. It detects all sorts of new line things, including the ones you didn't know existed. developer.apple.com/documentat

Rob Napier

@arroz @Catfish_Man Honestly, I had never thought of:

.split(whereSeparator: \.isNewline)

I'd gone round rubin's barn with Data and `UInt8(ascii: "\n")`, but `.isNewLine` is so much simpler. Thank you.

Michel Fortin

@cocoaphony And for a case where you really want to split purely on the \n:

"a\r\nb".unicodeScalars.split(separator: "\n").map { Substring($0) }

David Smith

@cocoaphony @arroz if you want the *really* neat version (…tooting my own horn here), check out url.resourceBytes.lines 😃

Marcin Krzyzanowski

@cocoaphony it has more consequences. I personally don't know what to think about. It convenient for one task and burden for task where each character matters

David Smith

@mmackh @cocoaphony that one's actually from Foundation, interestingly enough. I haven't checked if it's still implemented by bridging to ObjC but it may be.

The async sequence version (`.lines`) is likely way faster.

Go Up