Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • How can I create a String from UTF8 in Swift?
  • Is there a way to create a String from utf16 array in swift?
like image 244
Suragch Avatar asked Dec 13 '25 23:12

Suragch


1 Answers

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🐱
like image 100
Suragch Avatar answered Dec 15 '25 13:12

Suragch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!