Swift cannot assign 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 on the second line saying that it cannot assign an immutable value of type NSData. How do I go about converting the original variable data
to an encoded string SUTF8StringEncoding
?
source to share
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"
}
source to share
I don't quite understand what you are trying to achieve since it has not been explained what positionValue
(it is apparently some byte value).
Regardless, the error message comes from being used &
with a constant (generated let
). &
provides an unsafe pointer that allows you to manipulate the memory containing the constant value, but you cannot change the constant, which is why Swift throws an error message.
If you change the first line to read
var data = NSData(bytes: &positionValue, length: sizeof(UInt8))
then it is data
no longer a constant but a variable, and you can use &
with it.
Having said all this, since it data
contains the byte (s) you want to convert to a string, you can simply say
let data = NSData(bytes: &positionValue, length: sizeof(UInt8))
let dataString=NSString(data: data, encoding: NSUTF8StringEncoding)
source to share