Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selector vs Action Swift 4

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?

like image 352
user2511882 Avatar asked Jun 30 '17 00:06

user2511882


People also ask

What is a selector 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.

What is an action in Swift?

A swift event or process happens very quickly or without delay.

What is @objc function in Swift?

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.

What is IOS selector?

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.


1 Answers

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.

like image 87
OOPer Avatar answered Oct 21 '22 04:10

OOPer