2017-06-30 8 views
12

スウィフトの新機能。それはnotificationCenterのためにということですなぜセレクター対アクションスウィフト4

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"]!)") 

} 

し、最終的に

let x:UITapGestureRecognizer = UITapGestureRecognizer(target: self, 
    action: #selector(tapped)) 

self.addGestureRecognizer(x) 

func tapped(){ 
    print("tapped") 

    self.delegate!.theViewTapped() 

} 

:私は下の2つのスニペットがありますか? selectorパラメータには@objcタグを指定しますが、UITapGestureRecognizerアクションパラメータには指定しないでください。

SelectorAction inスイフトの違いは何ですか?

+0

の比較[Swift 4の#selector()で@objcの推論を非難するにはどうすればいいですか?](https://stackoverflow.com/q/44390378/2976878) - OOPerによると、両方の例ではターゲットメソッドは '@ objc'になります。 – Hamish

答えて

9

スウィフト4のためのこの提案をチェックしてください: SE-0160 Limiting @objc inference

案の記述によると、2番目のコードスニペットも@objcを必要とします。

実際に

、Xcodeの9ベータ2にバンドルスウィフト4コンパイラは#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

たぶん、あなたの第二は、あなたがより良いを考えるスウィフト4で使用する少し古すぎますセレクタを介して呼び出されるすべてのメソッドには、@objc属性が必要です。