Jack Amoratis
Jack Amoratis

Reputation: 672

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:

Hello
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!

Upvotes: 0

Views: 2198

Answers (2)

user887210
user887210

Reputation:

You can do this with escaped characters such as \n:

let secondaryString = "really"
let s = "Hello\nMy name is \(secondaryString) Jack!"
let find = Character("\n")
let r = String(s.characters.split(find).joinWithSeparator(["\\","n"]))
print(r) // -> "Hello\nMy name is really Jack!"

However, once the string s is generated the \(secondaryString) has already been interpolated to "really" and there is no trace of it other than the replaced word. I suppose if you already know the interpolated string you could search for it and replace it with "\\(secondaryString)" to get the result you want. Otherwise it's gone.

Upvotes: 1

Thilo
Thilo

Reputation: 262534

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.

Upvotes: 1

Related Questions