Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3.0 convert Data to Array<UInt8>

How to convert Data to array of UInt8?

func serialPort(_ serialPort: ORSSerialPort, didReceive data: Data) {
print("recieved:\(data)")
let arr: [UInt8] = Data(???)???
}

log recieved:70 bytes

like image 467
AleyRobotics Avatar asked Nov 10 '16 19:11

AleyRobotics


1 Answers

In Swift 3, Data works as a Collection of UInt8, so you can simply use Array.init.

var received: [UInt8] = []

func serialPort(_ serialPort: ORSSerialPort, didReceive data: Data) {
    print("received:\(data))")
    received = Array(data)
}

But, Array.init (or Array.append(contentsOf:)) copies the content of the Data, so it's not efficient when you need to work with huge size of Data.

like image 137
OOPer Avatar answered Oct 11 '22 02:10

OOPer