3

在 Swift 3.1 中,不推荐使用 UnsafeMutablePointer.initialize(from:)。Xcode 建议我改用 UnsafeMutableBufferPointer.initialize(from:) 。我有一个看起来像这样的代码块:

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

由于弃用,该代码给了我一个编译时警告。所以我要把它改成:

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

这是正确的方法吗?我只是想确保我做得正确。

4

1 回答 1

4

这是正确的,但您可以稍微简单地分配和初始化内存

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

创建缓冲区指针视图仍然很有用,因为它是一个集合,有一个count属性并且可以枚举:

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

for byte in buffer {
    // ...
}

但这与内存的初始化方式无关。

于 2017-04-30T18:00:43.470 回答