Search code examples
swiftcallbackbluetooth-lowenergycore-bluetooth

Why do Swift Argument Lables Matter for BLE Callback


I'm working on my first Swift / BLE app and noticed that if the argument labels for the disconnect call back of the central manager don't match or an "_" is used the call back is never fired. Being new to Swift am I was under the impression the labels are for readability only but apparently they are used to match function call backs. Is that accurate?

This works:

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

But removing or changing "didDisconnectPeripheral" to "didDisconnect" or "_" prevents the call back from happening.


Solution

  • The function centralManager(_:didDisconnectPeripheral:error:) is an optional method of the CBCentralManagerDelegate protocol meaning that you won't receive an error if you don't implement it when conforming to the protocol. However, the argument labels are part of the function signature, so removing them makes the function different than the protocol method and hence it won't be called by the protocol if you declare it using the wrong argument labels/names.

    You should however receive a warning stating that Instance method 'centralManager(central:didDisconnectPeripheral:error:)' nearly matches optional requirement 'centralManager(_:didDisconnectPeripheral:error:)' of protocol 'CBCentralManagerDelegate' if you change the function declaration to something that doesn't match the declaration in the protocol.