简体   繁体   English

在Swift 3.1中,不推荐使用UnsafeMutablePointer.initialize(from :)

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

In Swift 3.1, UnsafeMutablePointer.initialize(from:) is deprecated. 在Swift 3.1中,不推荐使用UnsafeMutablePointer.initialize(from :)。 Xcode suggests I use UnsafeMutableBufferPointer.initialize(from:) instead. Xcode建议我使用UnsafeMutableBufferPointer.initialize(来自:)。 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. 我只是想确保我正确地做到了。

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: 创建缓冲区指针视图仍然很有用,因为它是一个集合,具有count属性并且可以枚举:

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

for byte in buffer {
    // ...
}

but that is independent of how the memory is initialized. 但这与内存的初始化方式无关。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM