Swift 3.0将数据转换为数组<uint8>

时间:2016-11-10 19:44:07

标签: ios swift3 uint8array

如何将数据转换为UInt8数组?

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

日志 收到:70字节

3 个答案:

答案 0 :(得分:14)

在Swift 3中,Data作为Collection的{​​{1}},因此您只需使用UInt8

Array.init

但是,var received: [UInt8] = [] func serialPort(_ serialPort: ORSSerialPort, didReceive data: Data) { print("received:\(data))") received = Array(data) } (或Array.init)会复制Array.append(contentsOf:)的内容,因此当您需要处理大量Data时效率不高。

答案 1 :(得分:0)

知道了!

var recived = [UInt8]()

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

答案 2 :(得分:0)

使用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])
}