我无法在 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/