What's the difference between AnyObject and UIbutton as sender?

前端 未结 3 520
南笙
南笙 2020-12-29 09:48

When defining an IBAction, there\'s an option for Anyobject and UIButton, both works, what\'s the difference?

3条回答
  •  灰色年华
    2020-12-29 09:51

    If you are only ever going to use the function with a UIButton it is best practice to declare your sender as a UIButton. This saves you a bit of code and it also tells anyone in the future reading your code that you only expect the function to be used with a UIButton.

    Using AnyObject or Any will work, but you will need to do an guard let button = sender as? UIButton { return } in order to access it as a button. This way allows you to react differently depending on what the sender actually is, but I don't recommend doing that.

提交回复
热议问题