New to Swift. I have two snippets below:
NotificationCenter.default.addObserver(self,
selector:#selector(ViewController.notificationReceived),
name: Notification.Name(rawValue: name), object: nil)
@objc func notificationReceived(notification:Notification){
let x = notification.userInfo!
print("\(x["name"]!)")
}
and finally
let x:UITapGestureRecognizer = UITapGestureRecognizer(target: self,
action: #selector(tapped))
self.addGestureRecognizer(x)
func tapped(){
print("tapped")
self.delegate!.theViewTapped()
}
Why is it that for the notificationCenter
? I am supposed to provide the @objc
tag for the selector
parameter but not for the UITapGestureRecognizer
action parameter?
What exactly is the difference between Selector
and Action in
Swift?
Swift version: 5.6. Selectors are effectively the names of methods on an object or struct, and they are used to execute some code at runtime. They were common in Objective-C, but the earliest versions of Swift didn't include some core selector functionality so their use declined for a while.
A swift event or process happens very quickly or without delay.
That's where the @objc attribute comes in: when you apply it to a class or method it instructs Swift to make those things available to Objective-C as well as Swift code.
A selector is the name used to select a method to execute for an object, or the unique identifier that replaces the name when the source code is compiled. A selector by itself doesn't do anything. It simply identifies a method.
Check this proposal for Swift 4: SE-0160 Limiting @objc inference
According to the description in the proposal, your second code snippet also needs @objc
.
In fact, Swift 4 compiler bundled with Xcode 9 beta2 generates this error for the line using #selector(tapped)
:
error: argument of '#selector' refers to instance method 'tapped()' that is not exposed to Objective-C
note: add '@objc' to expose this instance method to Objective-C
Maybe your second is a little bit too old to use with Swift 4. You better think all methods invoked through selector need @objc
attribute.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With