简体   繁体   中英

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

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#>)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM