2017-06-04 108 views
0

我想UINT16轉換爲UINT8數組,但我得到了以下錯誤消息:如何將UInt16轉換爲Swift 3中的UInt8?

「初始化」不可用:使用「withMemoryRebound(到:容量:__)」來 暫時查看內存作爲另一個佈局兼容型。

代碼:

let statusByte: UInt8 = UInt8(status) 
    let lenghtByte: UInt16 = UInt16(passwordBytes.count) 

    var bigEndian = lenghtByte.bigEndian 

    let bytePtr = withUnsafePointer(to: &bigEndian) { 
     UnsafeBufferPointer<UInt8>(start: UnsafePointer($0), count: MemoryLayout.size(ofValue: bigEndian)) 
    } 

回答

3

作爲錯誤消息表示,則必須使用withMemoryRebound() 重新解釋指針UInt16作爲指針以UInt8

let bytes = withUnsafePointer(to: &bigEndian) { 
    $0.withMemoryRebound(to: UInt8.self, capacity: MemoryLayout.size(ofValue: bigEndian)) { 
     Array(UnsafeBufferPointer(start: $0, count: MemoryLayout.size(ofValue: bigEndian))) 
    } 
} 

封閉件與指針($0),其是唯一的調用有效期爲 ,並且不得傳遞給外部 供以後使用。這就是爲什麼Array被創建並用作返回值的原因。

然而有一個簡單的解決方案:

let bytes = withUnsafeBytes(of: &bigEndian) { Array($0) } 

說明:withUnsafeBytes調用與一個UnsafeRawBufferPointer封閉到bigEndian變量的存儲。 由於UnsafeRawBufferPointerSequenceUInt8,因此可以使用Array($0)創建一個數組 。

3

您可以擴展整數協議和創建數據屬性如下:

extension Integer { 
    var data: Data { 
     var source = self 
     return Data(bytes: &source, count: MemoryLayout<Self>.size) 
    } 
} 

在斯威夫特3數據符合MutableCollection所以你可以創建一個數組來自您的UInt16數據的字節:

extension Data { 
    var array: [UInt8] { return Array(self) } 
} 

let lenghtByte = UInt16(8) 
let bytePtr = lenghtByte.bigEndian.data.array // [0, 8] 
相關問題