Swift 5.0:不推荐使用'withUnsafeBytes':使用`withUnsafeBytes< R>(...) [英] Swift 5.0: 'withUnsafeBytes' is deprecated: use `withUnsafeBytes<R>(...)

查看:952
本文介绍了Swift 5.0:不推荐使用'withUnsafeBytes':使用`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中,DatawithUnsafeBytes()方法使用(无类型的)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.

还请注意,从Swift 4.2开始,您可以使用新的

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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆