Reputation: 4263
This is quite clear and works:
struct DEMO {
var used: Bool = false;
}
var a = DEMO()
var dataA = NSData(bytesNoCopy: &a, length: sizeof(DEMO))
This make sense because this method uses a CMutableVoidPointer.
Now use a const:
let b = DEMO(used:true)
var dataC = NSData(bytes: &b, length: sizeof(DEMO)) // ERROR
var dataB = NSData(bytesNoCopy: &b, length: sizeof(DEMO)) // ERROR
And you get an error on both init methodes, but why?
Do I really have to copy first a const into a var to use it?
var c = b
var dataC = NSData(bytes: &c, length: sizeof(DEMO))
I think this is why it is a similar problem within a function, you get a "let":
func test(data: DEMO) {
var c = NSData(bytes: data, length: sizeof(DEMO)) // ERROR
var b = NSData(bytes: &data, length: sizeof(DEMO)) // ERROR
var d = NSData(bytesNoCopy: data, length: sizeof(DEMO)) // ERROR
var a = NSData(bytesNoCopy: &data, length: sizeof(DEMO)) // ERROR
}
All of them deliver errors.
How to handle swift const with NSData?
Upvotes: 1
Views: 2416
Reputation: 4263
Based on Martin R comment I suggest a "work around" solution for the function part
func test(inout data: DEMO) {
var a = NSData(bytesNoCopy: &data, length: sizeof(DEMO),freeWhenDone:false)
....
}
The inout parameter provide at least a not cost version of data.
Upvotes: 1