(答案已针对 Swift 4 及更高版本进行了更新。)
使用 Swift 类型Data
,String
这可以作为
let myUInt32Array: [UInt32] = [72, 101, 108, 108, 111, 128049, 127465, 127466]
let data = Data(bytes: myUInt32Array, count: myUInt32Array.count * MemoryLayout<UInt32>.stride)
let myString = String(data: data, encoding: .utf32LittleEndian)!
print(myString) // Hello
此处使用强制展开,因为从 UTF-32 代码点到字符串的转换不会失败。
为方便起见,您可以定义String
扩展名
extension String {
init(utf32chars:[UInt32]) {
let data = Data(bytes: utf32chars, count: utf32chars.count * MemoryLayout<UInt32>.stride)
self = String(data: data, encoding: .utf32LittleEndian)!
}
}
并将其用作
let myUInt32Array: [UInt32] = [72, 101, 108, 108, 111, 128049, 127465, 127466]
let myString = String(utf32chars: myUInt32Array)
print(myString) // Hello
为了完整起见,来自https://stackoverflow.com/a/24757284/1187415的通用转换器
extension String {
init?<C : UnicodeCodec>(codeUnits:[C.CodeUnit], codec : C) {
var codec = codec
var str = ""
var generator = codeUnits.makeIterator()
var done = false
while !done {
let r = codec.decode(&generator)
switch (r) {
case .emptyInput:
done = true
case .scalarValue(let val):
str.unicodeScalars.append(val)
case .error:
return nil
}
}
self = str
}
}
可用于 UTF-8、UTF-16 和 UTF-32 输入。在你的情况下,它会是
let myUInt32Array: [UInt32] = [72, 101, 108, 108, 111, 128049, 127465, 127466]
let myString = String(codeUnits: myUInt32Array, codec : UTF32())!
print(myString) // Hello