在Swift中,如何将数据分配给UInt32数组? [英] In Swift, how does one assign Data to array of UInt32?

查看:224
本文介绍了在Swift中,如何将数据分配给UInt32数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有Swift代码,该代码读取一个表示一系列UInt32值的二进制文件,如下所示:

let fileData = binaryFile.readData(ofLength: 44)

guard fileData.count > 0 else { break }

let headerData = fileData.withUnsafeBytes {
    Array(UnsafeBufferPointer<UInt32>(start: $0, count: 11))
}

let polyCount = headerData[1].bigEndian
let polyFlags = headerData[2].bigEndian

我已经有一段时间没有使用包含此代码的程序了,但是最近返回它时,它仍然可以按预期运行,但是现在给出了弃用警告:

"withUnsafeBytes已过时:请改用withUnsafeBytes<R>(_: (UnsafeRawBufferPointer) throws -> R) rethrows -> R"

我已经花了很长时间寻找一种不成功的方法来完成此任务,但没有成功.网上有很多示例(包括stackoverflow中的示例),但几乎所有示例都是在此弃用生效之前编写的.坦白说,我炸了脑筋,尝试建议!我准备接受我遗漏了完全显而易见的内容(如果变得越来越复杂,说明您做错了."),但是我的工作环境除了这里没有其他人可以问..

任何指导将不胜感激.

解决方案

self.dataArray = data.withUnsafeBytes{ Array($0.bindMemory(to: UInt32.self))}

I have Swift code which reads a binary file representing a sequence of UInt32 values like this:

let fileData = binaryFile.readData(ofLength: 44)

guard fileData.count > 0 else { break }

let headerData = fileData.withUnsafeBytes {
    Array(UnsafeBufferPointer<UInt32>(start: $0, count: 11))
}

let polyCount = headerData[1].bigEndian
let polyFlags = headerData[2].bigEndian

I'd not used the program containing this code for a while, but when returning to it recently, it still works as expected, but now gives a deprecation warning:

"withUnsafeBytes is deprecated: use withUnsafeBytes<R>(_: (UnsafeRawBufferPointer) throws -> R) rethrows -> R instead"

I've searched for quite a long time for an un-deprecated way to do this without success. There are many examples across the web (including in stackoverflow) but almost all of them written before this deprecation into effect. Frankly, I've fried my brain hunting and trying suggestions! I am prepared to accept that I'm missing something totally obvious ("If it's getting complicated, you're doing it wrong."), but I work in an environment where I have no colleagues to ask .. except here.

Any guidance would be much appreciated.

解决方案

self.dataArray = data.withUnsafeBytes{ Array($0.bindMemory(to: UInt32.self))}

这篇关于在Swift中,如何将数据分配给UInt32数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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