swiftstringutf-8uint8array

Convert an array of UInt8 into a String in Swift


I have an array of UInt8 characters that I want to be combined into one cohesive String. I know String has the .utf8 property, and running a for loop over those characters was how I made the UInt8 array, but now I need the reverse of this.

For example, the UInt8 array:

[83, 87, 73, 70, 84]

and the desired end result:

"SWIFT"

Solution

  • You can simply use String bytes initializer:

    init?<S>(
        bytes: S,
        encoding: String.Encoding
    ) where S : Sequence, S.Element == UInt8
    

    Initializer
    init(bytes:encoding:)

    Creates a new string equivalent to the given bytes interpreted in >the specified encoding.

    String(bytes: [83, 87, 73, 70, 84], encoding: .utf8) // "SWIFT"