Tair Adibek
Tair Adibek

Reputation: 23

How can I convert unicode values in a string "U+XXXXXX" to the corresponding characters in Swift?

I accept from backend the following json

 {
        "id": "f33919f6-3554-4246-9e78-bca3a690c119",
        "title": "Category3",
        "slug": "category3",
        "hex_up": "#eb4034",
        "hex_down": "#80302a",
        "emoji": "U+1F602",
        "parent_id": "aa3f651b-f068-4ae1-a9d8-a18a9945b111"
    }

There is a field "emoji": "U+1F602",

I need show emoji icon like 😃 in UILabel I tried to google and found results like

let scalarValue = UnicodeScalar(emojiString)
let myString = String(scalarValue!)

Unfortunately app crashes at the second line. Thanks for your answers.

Upvotes: 2

Views: 394

Answers (3)

Leo Dabus
Leo Dabus

Reputation: 236458

You can simply apply a string transform from "Hex/Unicode" to "Any" (a set of all characters):

"U+1F602".applyingTransform(.init("Hex/Unicode-Any"), reverse: false)   // "😂"

or as instance properties of StringProtocol to encode/decode from/to hexa unicode:


extension StringTransform {
    static let unicodeToAny: Self = .init("Hex/Unicode-Any")
    static let anyToUnicode: Self = .init("Any-Hex/Unicode")
}

extension StringProtocol {
    var decodingHexaUnicode: String {
        applyingTransform(.unicodeToAny, reverse: false)!
    }
    var encodingHexaUnicode: String {
        applyingTransform(.anyToUnicode, reverse: false)!
    }
}

Usage:

let hexaUnicode = "U+1F602"
let emoji = hexaUnicode.decodingHexaUnicode       // "😂"
let unicodeFromEmoji = emoji.encodingHexaUnicode  // "U+1F602"

Upvotes: 3

The Swift Coder
The Swift Coder

Reputation: 442

The reason your app crashed is due to the fact that the scalarValue you attempted to initialize is nil, and you're force-unwrapping using (!) that nil value on line 2. Rob's answer shows how to unwrap the optional safely.

You can get the emoji by using the value following the U+. So you'll need to drop the first two characters of the string. So use this code to accomplish that:

let parsedEmoji = emojiString.substring(from:2)

Now you'll convert that emoji unicode using the code below.

let emoji = String(UnicodeScalar(Int(parsedEmojiHex,radix: 16)!)!)

print(emoji)

Upvotes: 0

Rob Napier
Rob Napier

Reputation: 299505

There's no U+... syntax in Swift. (There is a \u{...} syntax that does the same thing, but it's not necessary here.)

You'll need to parse the String yourself:

func parseUnicode(_ string: String) -> String? {
    guard string.hasPrefix("U+"), // Make sure it's a U+ string
          let value = Int(string.dropFirst(2), radix: 16), // Convert to Int
          let scalar = UnicodeScalar(value) // Convert to UnicodeScalar
          else { return nil }

    return String(scalar) // Convert to String
}

if let myString = parseUnicode(emoji) { ... }

Don't use ! here. The U+... string may be invalid, and you wouldn't want to crash in that case.

Upvotes: 3

Related Questions