ios - Swift 3 中的不安全指针

标签 ios swift xcode bluetooth unsafe-pointers

我知道这个问题被问了好几次,但我真的不明白。

我想从蓝牙设备(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 .

关于ios - Swift 3 中的不安全指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40111893/

相关文章:

swift - 如何快速连接字符串中的 "+"运算符

ios - addSubView当前uiview

ios - 在 iOS 中检查互联网连接的最佳方法

iphone - phonegap ipad/iphone,在两个设备上都有一个应用程序

swift - 将字符串转换为 UnsafeMutablePointer<UInt16>

swift - 在 Swift 中检索深度嵌套的 Firebase 数据

xcode - 错误:尝试 devtools::install_github() 时出现 "Could not find build tools necessary to build stringi"

ios - 如何快速在 UITableViewCell 中创建一个 facebook 注销按钮

objective-c - 如何在后台线程处理 MKNetworkKit 的数据?

ios - 在屏幕上不可见时删除 SKNode