Swift 中的 NSData 到 [Uint8] [英] NSData to [Uint8] in Swift
本文介绍了Swift 中的 NSData 到 [Uint8]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 Swift 中找不到这个问题的解决方案(它们都是 Objective-C,它们处理的指针我认为在 Swift 中不存在以相同的形式存在).有什么办法可以在Swift中将NSData
对象转换成[Uint8]
形式的字节数组?
I couldn't find a solution to this problem in Swift (all of them are Objective-C, and they deal with pointers which I don't think exist in Swift in the same form). Is there any way to convert a NSData
object into an array of bytes in the form of [Uint8]
in Swift?
推荐答案
你可以避免首先将数组初始化为占位符值,如果你以稍微复杂的方式处理指针,或者通过新的 Array
Swift 3 中引入的构造函数:
You can avoid first initialising the array to placeholder values, if you go through pointers in a slightly convoluted manner, or via the new Array
constructor introduced in 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))
}
斯威夫特 2
Array(UnsafeBufferPointer(start: UnsafePointer<UInt8>(data.bytes), count: data.length))
这篇关于Swift 中的 NSData 到 [Uint8]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文