[英]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。
您可以使用withUnsafeBytes
與pointee
:
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.