How to express Strings in Swift using Unicode hexadecimal values (UTF-16)

前端 未结 2 1599
[愿得一人]
[愿得一人] 2020-12-01 14:43

I want to write a Unicode string using hexadecimal values in Swift. I have read the documentation for String and Character so I know that I can use special Unicode character

相关标签:
2条回答
  • 2020-12-01 15:01

    from your Hex "0x1F52D" to actual Emoji

    let c = 0x1F602
    

    next step would possibly getting an Uint32 from your Hex

    let intEmoji = UnicodeScalar(c!).value
    

    from this you can do something like

    titleLabel.text = String(UnicodeScalar(intEmoji)!)
    

    here you have a "

    0 讨论(0)
  • 2020-12-01 15:14

    Updated for Swift 3

    Character

    The Swift syntax for forming a hexadecimal code point is

    \u{n}
    

    where n is a hexadecimal number up to 8 digits long. The valid range for a Unicode scalar is U+0 to U+D7FF and U+E000 to U+10FFFF inclusive. (The U+D800 to U+DFFF range is for surrogate pairs, which are not scalars themselves, but are used in UTF-16 for encoding the higher value scalars.)

    Examples:

    // The following forms are equivalent. They all produce "C". 
    let char1: Character = "\u{43}"
    let char2: Character = "\u{0043}"
    let char3: Character = "\u{00000043}"
    
    // Higher value Unicode scalars are done similarly
    let char4: Character = "\u{203C}" // ‼ (DOUBLE EXCLAMATION MARK character)
    let char5: Character = "\u{1F431}" //                                                                     
    0 讨论(0)
提交回复
热议问题