Convert UInt32 (UTF-32) to String in Swift

我怕爱的太早我们不能终老 提交于 2020-01-04 18:23:07

问题


I have an array of UInt32 values. I would like to convert this array to a String.

This doesn't work:

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)

These SO posts show UTF8 and UTF16:

  • How can I create a String from UTF8 in Swift?
  • Is there a way to create a String from utf16 array in swift?

回答1:


UnicodeScalar is a type alias for UInt32. So cast your UInt32 values to UnicodeScalar and then append them to a 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🐱



回答2:


(The answer has been updated for Swift 4 and later.)

Using the Swift type Data and String this can be done as

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🐱🇩🇪

A forced unwrap is used here because a conversion from UTF-32 code points to a string cannot fail.

You can define a String extension for your convenience

extension String {
    init(utf32chars:[UInt32]) {
        let data = Data(bytes: utf32chars, count: utf32chars.count * MemoryLayout<UInt32>.stride)
        self = String(data: data, encoding: .utf32LittleEndian)!
    }
}

and use it as

let myUInt32Array: [UInt32] = [72, 101, 108, 108, 111, 128049, 127465, 127466]
let myString = String(utf32chars: myUInt32Array)
print(myString) // Hello🐱🇩🇪

And just for completeness, the generic converter from 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
    }
}

can be used with UTF-8, UTF-16 and UTF-32 input. In your case it would be

let myUInt32Array: [UInt32] = [72, 101, 108, 108, 111, 128049, 127465, 127466]
let myString = String(codeUnits: myUInt32Array, codec : UTF32())!
print(myString) // Hello🐱🇩🇪


来源:https://stackoverflow.com/questions/31421054/convert-uint32-utf-32-to-string-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!