Natarajan
Natarajan

Reputation: 3271

How to use non printable characters in swift string variable?

I need to use non printable characters in a String constant, but Xcode shows error in my swift file as "Unprintable ASCII character found in source file"

My Simple code is below

let unprintableCharInString = "12345"

You could see the non printable characters at prefix and suffix of above string value, If you just copy paste my above code in Sublime text or some other text editor which supports to show Unprintable characters.

But if you paste the above code in Xcode swift file, you will see the compiler error "Unprintable ASCII character found in source file".

And if I use the same string in Objective C as like below, there is no error.

NSString *unprintableCharInString = @"12345";

So how to use non printable characters in Swift string variable directly as like above Objective C code?

Note: As the body text box trims those non printable chars while saving my question, you can't see those chars if you copy paste the code from here. Instead of that try to copy the above code by editing my question. So you can get those chars in Body text box during edit.

Screenshot from Sublime Text editor: enter image description here

Thanks in advance!

Upvotes: 3

Views: 2331

Answers (2)

Natarajan
Natarajan

Reputation: 3271

Based on the @Alladinian's suggestion in Comment above,

Answer is: We need to add the unprintable ASCII characters manually in source code while declaring string value.

Example:

let unprintableCharInString = "\u{02}123\u{1A}"

Here \u{02} is Hex value of "START OF TEXT (STX)" and \u{1A} is Hex value of "SUBSTITUTE (SUB)"

Thanks @Alladinian!

Upvotes: 2

Vyacheslav
Vyacheslav

Reputation: 27221

To display space characters you can use XCode Editor > Show Invisibles. But I'm not really sure will it help in your case.

Upvotes: 2

Related Questions