gpt4 book ai didi

swift - Swift 中的 NSData 到 [Uint8]

转载 作者:IT王子 更新时间:2023-10-29 04:58:33 25 4
gpt4 key购买 nike

我无法在 Swift 中找到这个问题的解决方案(它们都是 Objective-C,并且它们处理我认为在 Swift 中不存在的相同形式的指针)。有什么方法可以将 NSData 对象转换为 Swift 中 [Uint8] 形式的字节数组吗?

最佳答案

如果您以稍微复杂的方式遍历指针,或者通过 Swift 3 中引入的新 Array 构造函数,则可以避免首先将数组初始化为占位符值:

swift 3

let data = "foo".data(using: .utf8)!

// new constructor:
let array = [UInt8](data)

// …or old style through pointers:
let array = data.withUnsafeBytes {
[UInt8](UnsafeBufferPointer(start: $0, count: data.count))
}

swift 2

Array(UnsafeBufferPointer(start: UnsafePointer<UInt8>(data.bytes), count: data.length))

关于swift - Swift 中的 NSData 到 [Uint8],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31821709/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com