我以前在Swift 4.2中使用以下代码来生成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
在Swift 5中,使用(untyped)调用闭包的withUnsafeBytes()方法,您可以从原始内存中获取值:Data``UnsafeRawBufferPointerload()
withUnsafeBytes()
Data``UnsafeRawBufferPointer
load()
let value = data.withUnsafeBytes { $0.load(as: UInt32.self) }
(在Swift论坛中比较如何以明确定义的方式使用Data.withUnsafeBytes?)。请注意,这要求内存在4字节边界上_对齐_
另请注意,从Swift 4.2开始,您可以使用新RandomAPI轻松创建一个随机的32位整数:
Random
let randomId = UInt32.random(in: .min ... .max)