Convert array of unicode code points to string

2020-03-31 05:10发布

问题:

Given an array of strings that represent unicode code points:

let arr : [String] = ["0023", "FE0F", "20E3"]

How can I dynamically convert this into a swift string? Statically, I have found I can write:

let str = "\u{0023}\u{FE0F}\u{20E3}"

However, I would like to do this dynamically as each array will represent some sequence of code points. In the above example, the output would be #️⃣

回答1:

You can convert each of your hexa string to UInt32, initialise an Unicode.Scalar for each element and create a String UnicodeScalarView from it:

let arr = ["0023", "FE0F", "20E3"]
let values = arr.compactMap{ UInt32($0, radix: 16) }
let unicodeScalars = values.compactMap(Unicode.Scalar.init)
let string = String(String.UnicodeScalarView(unicodeScalars))

Which can be also be written as a one liner:

let arr = ["0023", "FE0F", "20E3"]
let string = String(String.UnicodeScalarView(arr.compactMap{ UInt32($0, radix: 16) }.compactMap(Unicode.Scalar.init)))

edit/update:

If all your strings can be represented by UInt16 values you can also use String initializer init(utf16CodeUnits: UnsafePointer<unichar>, count: Int)as shown by @MartinR here:

let arr = ["0023", "FE0F", "20E3"]
let values = arr.compactMap { UInt16($0, radix: 16) }
let string = String(utf16CodeUnits: values, count: values.count)  // "#️⃣"