How to convert UInt8 byte array to string in Swift

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")
}

Swifty solution

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

Hex representation:

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

Tags:

Arrays

Swift