Search code examples
iosswiftnsnotificationcenter

Swift: Default function parameter value via NotificationCenter


I have a function with default parameter value like this:

@objc func myFunc(theFlag: Bool = false) {

}

This function is called via notification center

NotificationCenter.default.addObserver(self, selector: #selector(myFunc), name: MyNotificationName, object: nil)

When MyNotificationName is posted, myFunc is called via notification center.

I assumed that the default value of theFlag is set to "false" and it works as I expected on most devices. However, I found that theFlag is set to "true" on 32bit devices.

I wonder if this was not a correct way to call a function with default value via notification center. Is there any official manner to do that?

I'm testing on Swift 4.1, Xcode 9.4.1


Solution

  • The correct way is

    @objc func myFunc(_ notification:Notification) // OR NSNotification also
    

    Don't expect the NotificationCenter.default to set a value for theFlag: Bool = false , with

    NotificationCenter.default.addObserver(self, selector: #selector(myFunc), name: MyNotificationName, object: nil)
    

    OR

    NotificationCenter.default.addObserver(self, selector: #selector(myFunc(_:)), name: MyNotificationName, object: nil)
    

    //

    If you want to send a value then insert it inside object / userInfo

    NotificationCenter.default.post(name:MyNotificationName, object:<#Here#>, userInfo:<#OrHere#>)