簡體   English   中英

Swift 3 中的 UnsafePointer

[英]UnsafePointer in Swift 3

我知道這個問題被問了好幾次,但我真的不明白。

我想從藍牙設備(miband)中提取一個值。 在 swift 2 中它是這樣工作的:

func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
    if characteristic.uuid.uuidString == "FF06" {
        let value = UnsafePointer<Int>(characteristic.value!.bytes).memory
        print("Steps: \(value)")
    }
}

但是在 swift 3 中它會拋出一個錯誤:

Cannot invoke initializer for type 'UnsafePointer<Int>' with an argument list of type '(UnsafeRawPointer)'

而且我不知道如何將其遷移到 swift 3。

您可以使用withUnsafeBytespointee

func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
    if characteristic.uuid.uuidString == "FF06" {
        let value = characteristic.value!.withUnsafeBytes { (pointer: UnsafePointer<Int>) -> Int in
            return pointer.pointee
        }
        print("Steps: \(value)")
    }
}

如果UnsafePointer指着的數組Pointee ,則可以使用下標操作符,例如pointer[0] pointer[1]等等,而不是pointer.pointee

有關更多信息,請參閱SE-0107

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM