Jimmery Jimmery - 14 days ago 5x
Swift Question

Casting Any to AnyObject in Swift

I have an object contained within a Dictionary like so:

let dict:<String, Any> = ["obj": self]

Then later on I am trying to use that object as the target of a button press:

button.addTarget(dict["obj"], action: "buttonPress:", forControlEvents: .TouchUpInside)

And I get the error:

Type '(String, Any)' does not conform to protocol 'AnyObject'

I am guessing here my issue is trying to cast
. Is this even possible?


No downcasting from Any to AnyObject is not possible, and yes, the problem you have is about Any not convertible to AnyObject.

Any can represent any type (classes, structs, enums, ints, strings etc.), whereas AnyObject can represent reference types only (i.e. classes).

To solve the problem, I think you should change your dictionary to store values of AnyObject type:

let dict:<String, AnyObject> = ["obj": self]

Note that even if the dictionary contains AnyObject values, it can also store:

  • numbers
  • strings
  • arrays
  • dictionaries

because these types are automatically bridged to the corresponding objc types (NSNumber, NSArray, NSDictionary, etc.)

If you really need to have max flexibility, then I suggest using NSDictionary - but in that case value types must be explicitly boxed in reference types (i.e. int in NSNumber, etc.).

Also @rintaro's answer in another good option.