首页 > 解决方案 > 为什么 Swift 参数标签对 BLE 回调很重要

问题描述

我正在开发我的第一个 Swift / BLE 应用程序,并注意到如果中央管理器的断开连接回调的参数标签不匹配或使用“_”,则永远不会触发回调。作为 Swift 的新手,我的印象是这些标签只是为了便于阅读,但显然它们是用来匹配函数回调的。那准确吗?

这有效:

 // Called when disconnected from BLE device
func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?)

但是将“didDisconnectPeripheral”删除或更改为“didDisconnect”或“_”会阻止回调发生。

标签: swiftcallbackbluetooth-lowenergycore-bluetooth

解决方案


该函数centralManager(_:didDisconnectPeripheral:error:)CBCentralManagerDelegate协议的可选方法,这意味着如果您在符合协议时不实现它,您将不会收到错误。但是,参数标签是函数签名的一部分,因此删除它们会使函数与协议方法不同,因此如果您使用错误的参数标签/名称声明它,协议将不会调用它。

但是,您应该收到一条警告,说明Instance method 'centralManager(central:didDisconnectPeripheral:error:)' nearly matches optional requirement 'centralManager(_:didDisconnectPeripheral:error:)' of protocol 'CBCentralManagerDelegate'如果您将函数声明更改为与协议中的声明不匹配的内容。


推荐阅读