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

穿精又带淫゛_ 提交于 2020-01-14 14:55:27

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/43709407/in-swift-3-1-unsafemutablepointer-initializefrom-is-deprecated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!