Swift 5.0:不推荐使用“withUnsafeBytes":使用“withUnsafeBytes<R>(...) [英] Swift 5.0: 'withUnsafeBytes' is deprecated: use `withUnsafeBytes<R>(...)
问题描述
我之前在 Swift 4.2 中使用过这段代码来生成一个 id:
I previously used this code in Swift 4.2 to generate an id:
public static func generateId() throws -> UInt32 {
let data: Data = try random(bytes: 4)
let value: UInt32 = data.withUnsafeBytes { $0.pointee } // deprecated warning!
return value // + some other stuff
}
withUnsafeBytes
在 Swift 5.0 中已弃用.我该如何解决这个问题?
withUnsafeBytes
is deprecated on Swift 5.0. How can I solve this?
推荐答案
在 Swift 5 中,Data
的 withUnsafeBytes()
方法用一个(无类型的)<代码>UnsafeRawBufferPointer,你可以load()代码>
原始内存中的值:
In Swift 5 the withUnsafeBytes()
method of Data
calls the closure with an (untyped) UnsafeRawBufferPointer
, and you can load()
the value from the raw memory:
let value = data.withUnsafeBytes { $0.load(as: UInt32.self) }
(比较 如何以明确定义的方式使用 Data.withUnsafeBytes? 在 Swift 论坛中).请注意,这要求内存在 4 字节边界上对齐.有关替代方案,请参阅往返 Swift 数字类型到/从数据.
(compare How to use Data.withUnsafeBytes in a well-defined manner? in the Swift forum). Note that this requires that the memory is aligned on a 4-byte boundary. For alternatives see round trip Swift number types to/from Data.
另请注意,从 Swift 4.2 开始,您只需使用新的 Random
API:
Note also that as of Swift 4.2 you can create a random 32-bit integer simply using the new Random
API:
let randomId = UInt32.random(in: .min ... .max)
这篇关于Swift 5.0:不推荐使用“withUnsafeBytes":使用“withUnsafeBytes<R>(...)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!