Swift 3.0 数据转数组<UInt8>

Swift 3.0 convert Data to Array<UInt8>

如何将Data转为UInt8数组?

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

日志 recieved:70 字节

知道了!

var recived = [UInt8]()

func serialPort(_ serialPort: ORSSerialPort, didReceive data: Data) {
        recived.removeAll()
        print("recieved:\(data))")
        recived.append(contentsOf: data)
}

使用withUnsafeBytes:

let data = "ABCD".data(using: .ascii)!
data.withUnsafeBytes {  (pointer: UnsafePointer<UInt8>) in
    //Prints 67 which is the ASCII value of 'C'
    print(pointer[2])
}

在 Swift 3 中,Data 相当于 UInt8Collection,因此您可以简单地使用 Array.init.

var received: [UInt8] = []

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

但是,Array.init(或Array.append(contentsOf:))复制了Data的内容,所以当你需要处理Data的大尺寸时效率不高。