NSData from Byte array in Swift

var foo : Byte[] = [0xff, 0xD9]

var data = NSData(bytes: foo, length: foo.count)

println("\(data)")

outputs: ff d9

var data = NSData(bytes: [0xFF, 0xD9] as Byte[], length: 2)

println("\(data)")

outputs: ff d9

Edit: Ah, you have to write 'as Byte[]', so then the results are the same


UPDATED for Swift 2.2

var foo:[UInt8] = [0xff, 0xD9]
var data = NSData(bytes: foo, length: foo.count)
print("\(data)")

outputs: ff d9

var data = NSData(bytes: [0xFF, 0xD9] as [UInt8], length: 2)
print("\(data)")

outputs: ff d9


You don't need to extend Data, in Swift 3 you can do this:

let bytes:[UInt8] = [0x00, 0x01, 0x02, 0x03]
let data = Data(bytes: bytes)
print(data as NSData)

Prints "<00010203>"

To get the byte array again:

let byteArray:[UInt8] = [UInt8](data)

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.

Tags:

Ios

Swift