Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
811 views
in Technique[技术] by (71.8m points)

swift - Convert array of unicode code points to string

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 #??

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)  // "#??"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...