swiftstringnsstringfoundationnsstringencoding

Swift String including Special Characters


I have a user enter a multi string in an NSTextView.

var textViewString = textView.textStorage?.string

Printing the string ( print(textViewString) ), I get a multi-line string, for example:

hello this is line 1 

and this is line 2

I want a swift string representation that includes the new line characters. For example, I want print(textStringFlat) to print:

hello this is line 1\n\nand this is line 2

What do I need to do to textViewString to expose the special characters?


Solution

  • If you just want to replace the newlines with the literal characters \ and n then use:

    let escapedText = someText.replacingOccurrences(of: "\n", with: "\\n")