Victor Yip Victor Yip - 7 days ago 9
Swift Question

Swift unable to connect multiple buttons via IBAction "Any" but okay via "AnyObject"

I am building an app with 9 buttons. I am trying to connect it to one IBaction below, which does not work (No UI update in assistant editor to let me connect the button and this IBAction code block).

@IBAction func buttonPressed(_ sender: Any) {

print("ButtonPressed")

}


enter image description here

It works however with "AnyObject" after sender.

@IBAction func buttonPressed(_ sender: AnyObject) {

print("ButtonPressed")

}


enter image description here

Question 1, why is this behavior?

Question 2, what is the difference between Any and AnyObject in Swift?

Based on swift_documentation, any allows objects of various types while anyObject allows only objects of the same type. In this case, i believe it means that the sender object has to be of the same type for any.

Does this mean connecting multiple buttons is only allowed for buttons of the same type therefore only anyObject works?

Answer

Last things first :)

The Difference

If you look at the description of Any and AnyObject in The Swift Programming Language you'll find this description:

  • Any can represent an instance of any type at all, including function types.

  • AnyObject can represent an instance of any class type.

Why this behaviour

I'm guessing here but @IBAction is part of the Target-Action pattern used by Apple for communicating between different elements of your app (targets know how to relate to actions). As this pattern predates Swift I'm guessing the sender of an action has to be a class for this to work. In Objective C you would use id, meaning "Any Class", and in Swift - as we've just found out - the representation of "Something that can be of type any class" is AnyObject.

Hope that makes sense and helps you.

Comments