3

我有一组UInt32值。我想将此数组转换为String.

这不起作用:

let myUInt32Array: [UInt32] = [72, 101, 108, 108, 111, 128049]
let myString = String(myUInt32Array) // error
let myString = String(stringInterpolationSegment: myUInt32Array) // [72, 101, 108, 108, 111, 128049] (not what I want)

这些 SO 帖子显示UTF8UTF16

4

2 回答 2

4

UnicodeScalar是 的类型别名UInt32。因此,将您的UInt32值转换为UnicodeScalar,然后将它们附加到String.

let myUInt32Array: [UInt32] = [72, 101, 108, 108, 111, 128049]

var myString: String = ""

for value in myUInt32Array {
    if let scalar = UnicodeScalar(value) {
        myString.append(Character(scalar))
    }
}

print(myString) // Hello
于 2015-07-15T03:34:47.667 回答
3

(答案已针对 Swift 4 及更高版本进行了更新。)

使用 Swift 类型DataString这可以作为

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
于 2015-07-15T07:13:46.623 回答