Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Swift 3.1, UnsafeMutablePointer.initialize(from:) is deprecated

In Swift 3.1, UnsafeMutablePointer.initialize(from:) is deprecated. Xcode suggests I use UnsafeMutableBufferPointer.initialize(from:) instead. I have a code block that looks like this:

let pointer = UnsafeMutablePointer<UInt8>.allocate(capacity: 64)
pointer.initialize(from: repeatElement(0, count: 64))

The code gives me a compile time warning because of the deprecation. So I'm going to change that to:

let pointer = UnsafeMutablePointer<UInt8>.allocate(capacity: 64)
let buffer = UnsafeMutableBufferPointer(start: pointer, count: 64)
_ = buffer.initialize(from: repeatElement(0, count: 64))

Is this the right way to do this? I just wanted to make sure that I'm doing it correctly.

like image 514
Jake Avatar asked Dec 17 '25 12:12

Jake


1 Answers

It is correct, but you can allocate and initialize memory slightly simpler with

let pointer = UnsafeMutablePointer<UInt8>.allocate(capacity: 64)
pointer.initialize(to: 0, count: 64)

Creating a buffer pointer view can still be useful because that is a collection, has a count property and can be enumerated:

let buffer = UnsafeMutableBufferPointer(start: pointer, count: 64)

for byte in buffer {
    // ...
}

but that is independent of how the memory is initialized.

like image 62
Martin R Avatar answered Dec 19 '25 04:12

Martin R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!