arraysswift

How to convert UInt8 byte array to string in Swift


I am facing problems while converting UInt8 Byte array to string in swift. I have searched and find a simple solution

String.stringWithBytes(buff, encoding: NSUTF8StringEncoding)

but it is showing error String.type does not have a member stringWithBytes. Can anyone suggest me a solution ?

this is my code where i am getting anNSData and converted into bytes array and then i have to convert that byte array into string.

let count = data.length / sizeof(UInt8)
var array = [UInt8](count: count, repeatedValue: 0)
data.getBytes(&array, length:count * sizeof(UInt8))
String.stringWithBytes(buff, encoding: NSUTF8StringEncoding)

Solution

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