13

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?

clemens
  • 16,716
  • 11
  • 50
  • 65
user2511882
  • 9,022
  • 10
  • 51
  • 59
  • Compare [How can I deal with @objc inference deprecation with #selector() in Swift 4?](https://stackoverflow.com/q/44390378/2976878) – as OOPer says, both examples require the target method to be `@objc`. – Hamish Jun 30 '17 at 09:27

1 Answers1

10

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.

OOPer
  • 47,149
  • 6
  • 107
  • 142