user2511882
user2511882

Reputation: 9152

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?

Upvotes: 13

Views: 20367

Answers (1)

OOPer
OOPer

Reputation: 47896

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.

Upvotes: 10

Related Questions