Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSData from Byte array in Swift

Tags:

ios

swift

I'm trying to create an NSData var from an array of bytes.

In Obj-C I might have done this:

NSData *endMarker = [[NSData alloc] initWithBytes:{ 0xFF, 0xD9 }, length: 2]

I can't figure out a working equivalent in Swift.

like image 924
Jeff Avatar asked Jun 13 '14 02:06

Jeff


1 Answers

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) 

You can read more about unsafe pointer parameters in Apple's Interacting with C APIs documentation.

like image 86
Nate Cook Avatar answered Sep 29 '22 05:09

Nate Cook