I had this:
let alphaPtr = UnsafeMutablePointer(mutating: alpha) as UnsafeMutablePointer?
W
It was never safe to do this, and the compiler now is warning you more aggressively.
let alphaPtr = UnsafeMutablePointer ...
At the end of this line, alphaPtr
is already invalid. There is no promise that what it points to is still allocated memory.
Instead, you need to nest whatever usage you need into a withUnsafeMutablePointer()
(or withUnsafePointer()
) block. If you cannot nest it into a block (for example, if you were storing the pointer or returning it), there is no way to make that correct. You'll have to redesign your data management to not require that.
Do you need use the withUnsafeBufferPointer
method from Array as
var alphaPtr: UnsafeBufferPointer = alpha.withUnsafeBufferPointer { $0 }
that's command produce a pointer optional if you need working with a specific type could you you use bindMemory(to:)
or other function that match with you requirements.
Sometimes use a &alpha
if you need a UnsafeRawPointer
as a function parameter.
Try this
var bytes = [UInt8]()
let uint8Pointer = UnsafeMutablePointer<UInt8>.allocate(capacity: bytes.count)
uint8Pointer.initialize(from: &bytes, count: bytes.count)