简体   繁体   中英

Building Unicode scalar String in Swift

How can I make "\\u{3A9}" String with coding? here what I tried, but did not worked!

let omegaHexadecimal: String = "3A9"
let omega = "\u{" + omegaHexadecimal + "}"

Or:

let omegaHexadecimal: String = "3A9"
let omega = "\u{\(omegaHexadecimal)}"

Update:

extension StringProtocol where Self: RangeReplaceableCollection {

    private var decodingUnicodeCharacters: String { applyingTransform(.init("Hex-Any"), reverse: false) ?? "" }

    func stringToUniCodeHexConvertor(upTo lenght: Int = 4, using character: Character = "0") -> String {
        
        return ("\\u" + repeatElement(character, count: Swift.max(0,lenght-count)) + self).decodingUnicodeCharacters
    }

}

let omegaHexadecimal: String = "3A9"
let omega = omegaHexadecimal.stringToUniCodeHexConvertor()
print(omega)   // "Ω"

You can pad your string up to 4 hexa digits (2 bytes UInt16), add \\u\u003c/code> prefix \\uXXXX and use a string transform to convert your unicode hexa value to the corresponding character:

extension StringProtocol where Self: RangeReplaceableCollection {
    func paddingToLeft(upTo lenght: Int = 4, using character: Character = "0") -> Self {
        repeatElement(character, count: Swift.max(0,lenght-count)) + self
    }
    var decodingUnicodeCharacters: String { applyingTransform(.init("Hex-Any"), reverse: false) ?? "" }
}

let omegaHexadecimal: String = "3A9"
let omega = "\\u" + omegaHexadecimal.paddingToLeft()  //  "\\u03A9"

omega.decodingUnicodeCharacters   // "Ω"

Why so complicated? Work with numbers directly:

let omega = UnicodeScalar(0x3A9)!
print(String(omega)) // Ω

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM