How to convert UInt8 byte array to string in Swift

Solution 1:

Update for Swift 3/Xcode 8:

String from bytes: [UInt8]:

if let string = String(bytes: bytes, encoding: .utf8) {
    print(string)
} else {
    print("not a valid UTF-8 sequence")
}

String from data: Data:

let data: Data = ...
if let string = String(data: data, encoding: .utf8) {
    print(string)
} else {
    print("not a valid UTF-8 sequence")
}

Update for Swift 2/Xcode 7:

String from bytes: [UInt8]:

if let string = String(bytes: bytes, encoding: NSUTF8StringEncoding) {
    print(string)
} else {
    print("not a valid UTF-8 sequence")
}

String from data: NSData:

let data: NSData = ...
if let str = String(data: data, encoding: NSUTF8StringEncoding) {
    print(str)
} else {
    print("not a valid UTF-8 sequence")
}

Previous answer:

String does not have a stringWithBytes() method. NSString has a

 NSString(bytes: , length: , encoding: )

method which you could use, but you can create the string directly from NSData, without the need for an UInt8 array:

if let str = NSString(data: data, encoding: NSUTF8StringEncoding) as? String {
    println(str)
} else {
    println("not a valid UTF-8 sequence")
}

Solution 2:

Swifty solution

array.reduce("", combine: { $0 + String(format: "%c", $1)})

Hex representation:

array.reduce("", combine: { $0 + String(format: "%02x", $1)})

Solution 3:

Update for Swift 5.2.2:

String(decoding: yourByteArray, as: UTF8.self)

Solution 4:

This worked for me:

String(bytes: bytes, encoding: NSUTF8StringEncoding)

Solution 5:

This solution works.

NSString(bytes: data!, length: data!.count, encoding: NSUTF8StringEncoding)