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
调用闭包,您可以
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.
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屋!