When defining an IBAction, there's an option for Anyobject and UIButton, both works, what's the difference?
If you want to use a property of the sender that is specific to the class UIButton, like sender.currentTitle, the compiler will object if it does not know that the sender is a UIButton. So you have to 'cast' the sender into UIButton either before the property is referenced or as your question suggests, in the method call itself.
In ObjectiveC the class is typically listed as (id). I assume that is what Swift means by "Any". If you know that the action will only be called by a UIButton then you can make that (UIButton *) in ObjectiveC and I assume that is the same as Swift's UIButton.
It’s equivalent to ‘id’ in Objective-C. AnyObject can represent an instance of any class type. If you specifically define the array as [ AnyObject ], you are indicating to the compiler that you are aware that the elements are of the reference data type only.
If you need to know who sent the message inside the IBAction, use sender: UIButton Otherwise, you can use Any, that will make no difference. I usually prefer to know who the sender is.
Yes, both works. The difference is just that by declaring it to a button, you get a typecasted reference as UIButton instead of AnyObject (or id in Objective-C). If you did not do that you will have to do it manually inside the code.
You should prefer leaving it to AnyObject in case the action has some code you would like to call from anywhere else, rather than just the button action.
For example a refresh button, you might have to do a refresh programatically. If you have set your action parameter to UIButton, you have to send an UIButton (but why??? You are doing it programatically, right?). Whereas if it is AnyObject, you can send 'self'. Which will also make you distinguish whether the refresh was done on action or programatically.
Hope that explains. Sorry for no code. I am not into Swift coding much. Edits are welcome.
EDIT
So, even if it is AnyObject, it does have your UIButton properties. Just type cast it to use them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With