timman
timman

Reputation: 489

Is there a reason to ever choose sender: Any when creating an @IBAction in Swift?

The sender type is set to Any by default when you use IB/storyboards in Xcode to create an IBAction linking the interface object (e.g. button) with the method in the code file.

Since you are doing this from the interface to the code, Xcode should know by the interface what type of control you are using, for example a UIButton, and so why does it automatically set the sender to the Any type and not to UIButton specifically?

Is there any reason to leave it as Any and not change it to the UIButton type instead at the point of creation? Either when you do it from the interface to the code, or when you create the IBAction in the code first?

Basic example of the code you get when hooking up a button to your view controller, despite control clicking from the button on the interface:

@IBAction func playAgain(_ sender: Any) {}

Upvotes: 1

Views: 733

Answers (1)

Alexander
Alexander

Reputation: 63271

I think it's an unreasonable default. If your function only applies to a single UI control, then the sender should be as strongly typed as possible.

Technically, you could define a single @IBAction, and bind it to multiple UI controls, of different types. But even in such a case, a more specific type like NSView would be more appropriate than Any.

Upvotes: 4

Related Questions