Search code examples
iosswiftencodinghexnsdata

Swift Cannot Assign to immutable value of type NSData


I have

let data = NSData(bytes: &positionValue, length: sizeof(UInt8))

and

let dataString=NSString(bytes: &data, length: sizeof(UInt8), encoding: NSUTF8StringEncoding)

Unfortunately the compiler throws an error at the second line, saying that it can't assign to immutable value of type NSData. How would I go about converting my original data variable to a string with encoding SUTF8StringEncoding?


Solution

  • update: Xcode 7.2 • Swift 2.1.1

    let myTestString = "Hello World"
    
    // converting from string to NSData
    if let myStringData = myTestString.dataUsingEncoding(NSUTF8StringEncoding) {
    
        // converting from NSData to String
        let myStringFromData = String(data: myStringData, encoding: NSUTF8StringEncoding) ?? "Hello World"
    }