Home > Net >  When passing a struct by reference (as an UnsafeRawPointer) why must it be from a `var`?
When passing a struct by reference (as an UnsafeRawPointer) why must it be from a `var`?

Time:09-22

Why does &copy in the below code need to be based on a var, why can't it be a let?

var mutableCopy = instanceOfA 
let data = Data(bytes: &mutableCopy, count: MemoryLayout.size(ofValue: instanceOfA))

let immutableCopy = instanceOfA 
// Cannot pass immutable value as inout
let data = Data(bytes: &immutableCopy, count: MemoryLayout.size(ofValue: instanceOfA)) 

Edit: To avoid confusion: I'm totally aware of how inout works. My problem is that the Data.init(bytes:,count:) doesn't take an inout but just a plain UnsafeRawPointer and since it's not mutable, why does it require a var rather than a let?

CodePudding user response:

From the Apple document of UnsafeRawPointer:-

Implicit Casting and Bridging:-

When calling a function or method with an UnsafeRawPointer parameter, you can pass an instance of that specific pointer type, pass an instance of a compatible pointer type, or use Swift’s implicit bridging to pass a compatible pointer.

Now what you have used is implicit bridging. You can use Swift’s implicit bridging to pass a pointer to an instance or to the elements of an array. Now inout is used to implicitly create a pointer to an instance of any type and inout cannot be constant so you need to declare your instance as var.

  • Related