Swift中字节数组的NSData [英] NSData from Byte array in Swift
问题描述
我正在尝试从字节数组中创建一个NSData
var
.
I'm trying to create an NSData
var
from an array of bytes.
在Obj-C中,我可能已经这样做了:
In Obj-C I might have done this:
NSData *endMarker = [[NSData alloc] initWithBytes:{ 0xFF, 0xD9 }, length: 2]
我无法弄清楚Swift中的等效功能.
I can't figure out a working equivalent in Swift.
推荐答案
NSData
具有一个带有bytes
指针的初始化程序:init(bytes: UnsafeMutablePointer <Void>, length: Int)
. UnsafePointer
参数可以接受各种不同的东西,包括一个简单的Swift数组,因此您可以使用与Objective-C几乎相同的语法.传递数组时,需要确保将其标识为UInt8
数组,否则Swift的类型推断将假定您要创建Int
数组.
NSData
has an initializer that takes a bytes
pointer: init(bytes: UnsafeMutablePointer <Void>, length: Int)
. An UnsafePointer
parameter can accept a variety of different things, including a simple Swift array, so you can use pretty much the same syntax as in Objective-C. When you pass the array, you need to make sure you identify it as a UInt8
array or Swift's type inference will assume you mean to create an Int
array.
var endMarker = NSData(bytes: [0xFF, 0xD9] as [UInt8], length: 2)
您可以在Apple的与C进行交互中阅读有关不安全指针参数的更多信息. API 文档.
You can read more about unsafe pointer parameters in Apple's Interacting with C APIs documentation.
这篇关于Swift中字节数组的NSData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!