Jack Amoratis Jack Amoratis - 1 year ago 153
Swift Question

In Swift how to obtain the "invisible" escape characters in a string variable into another variable

In Swift I can create a String variable such as this:

let s = "Hello\nMy name is Jack!"

And if I use s, the output will be:

My name is Jack!

(because the \n is a linefeed)

But what if I want to programmatically obtain the raw characters in the s variable? As in if I want to actually do something like:

let sRaw = s.raw

I made the .raw up, but something like this. So that the literal value of sRaw would be:

Hello\nMy name is Jack!

and it would literally print the string, complete with literal "\n"

Thank you!

Answer Source

The newline is the "raw character" contained in the string.

How exactly you formed the string (in this case from a string literal with an escape sequence in source code) is not retained (it is only available in the source code, but not preserved in the resulting program). It would look exactly the same if you read it from a file, a database, the concatenation of multiple literals, a multi-line literal, a numeric escape sequence, etc.

If you want to print newline as \n you have to convert it back (by doing text replacement) -- but again, you don't know if the string was really created from such a literal.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download