3

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?

Ross M.
  • 313
  • 2
  • 13

2 Answers2

3

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"
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • Thanks Leonardo! This worked for me. Also, both of you said the same thing but Paul answered later so that's why I chose yours as the answer. – Ross M. Apr 23 '15 at 04:20
3

I am not exactly clear what you are trying to achieve, as it isn't explained what positionValue is (it seems to be some byte value).

Regardless, the error message arises from your use of & with a constant (created by let). & provides an unsafe pointer, which allows manipulation of the memory containing the constant's value, but you can't change a constant, so Swift gives an error message.

If you change the first line to read

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

then data is no longer a constant, but a variable and you can use & with it.

Having said all that, since data contains the byte(s) you want to convert to a string you can just say

let data = NSData(bytes: &positionValue, length: sizeof(UInt8))
let dataString=NSString(data: data, encoding: NSUTF8StringEncoding)
Paulw11
  • 108,386
  • 14
  • 159
  • 186