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

前端 未结 2 1610
[愿得一人]
[愿得一人] 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: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}" // 

提交回复
热议问题