Swift 3.0 convert Data to Array<UInt8>

自古美人都是妖i 提交于 2020-06-27 08:54:09

问题


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


回答1:


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.




回答2:


Got it!

var recived = [UInt8]()

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



回答3:


Use 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])
}


来源:https://stackoverflow.com/questions/40535774/swift-3-0-convert-data-to-arrayuint8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!