问题
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