0

I've reproduced this problem in a Swift playground but haven't solved it yet...

I'd like to print one of a range of characters in a UILabel. If I explicitly declare the character, it works:

// This works.
let value: String = "\u{f096}"
label.text = value  // Displays the referenced character.

However, I want to construct the String. The code below appears to produce the same result as the line above, except that it doesn't. It just produces the String \u{f096} and not the character it references.

// This doesn't work
let n: Int = 0x95 + 1
print(String(n, radix: 16))  // Prints "96".
let value: String = "\\u{f0\(String(n, radix: 16))}"
label.text = value  // Displays the String "\u{f096}".

I'm probably missing something simple. Any ideas?

Vince O'Sullivan
  • 2,611
  • 32
  • 45
  • 1
    Could be just the excess "\" in `"\\u{f0\(String(n,radix: 16))}"`? Just guessing - I have no idea how string formats work in swift. – Filburt Oct 12 '16 at 08:53
  • Agreed it could be but then it doesn't compile. That's why I reproduced the problem in a playground before posting. I get the error: Scratch.playground:7:27: Expected '}' in \u{...} escape sequence – Vince O'Sullivan Oct 12 '16 at 08:56
  • Maybe [How to create a string with format](http://stackoverflow.com/a/24097543/205233) has a hint. – Filburt Oct 12 '16 at 08:58
  • Same problem. The initial backslash still needs to be escaped and the resulting String comes out as as "\u{f096}" not the required character. – Vince O'Sullivan Oct 12 '16 at 09:03

1 Answers1

3

How about stop using string conversion voodoo and use standard library type UnicodeScalar?

You can also create Unicode scalar values directly from their numeric representation.

let airplane = UnicodeScalar(9992)
print(airplane) 
// Prints "✈︎"

UnicodeScalar.init there is actually returning optional value, so you must unwrap it.

If you need String just convert it via Character type to String.

let airplaneString: String = String(Character(airplane)) // Assuming that airplane here is unwrapped
user28434'mstep
  • 6,290
  • 2
  • 20
  • 35