Search code examples
iosstringswiftuint32

Convert UInt32 (UTF-32) to String in Swift


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:


Solution

  • 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🐱