Reputation: 6477
I searched many answers for similar questions but can't find the right answer that fixes this. I have a very simple struct
struct MyParameters {
var position: CGPoint
var size: Float
}
And then this initialisation
var parameters = MyParameters(position: .zero, size: 0)
let pointer = UnsafeMutableRawPointer(¶meters)
And I get a warning in the second line
Initialization of 'UnsafeMutableRawPointer' results in a dangling pointer
I understand the compiler is complaining as it is not sure whether the memory pointed to by the pointer will continue to exist. But what is the right way to pass pointers in that case?
Upvotes: 0
Views: 288
Reputation: 17844
Use withUnsafeMutableBytes
func foo() {
var parameters = MyParameters(position: .zero, size: 0)
withUnsafeMutableBytes(of: ¶meters) { pointer in
// here the lifetime is known
}
}
Upvotes: 1