I have an object contained within a Dictionary like so:
let dict:<String, Any> = ["obj": self]
button.addTarget(dict["obj"], action: "buttonPress:", forControlEvents: .TouchUpInside)
Type '(String, Any)' does not conform to protocol 'AnyObject'
No downcasting from
AnyObject is not possible, and yes, the problem you have is about
Any not convertible to
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
let dict:<String, AnyObject> = ["obj": self]
Note that even if the dictionary contains
AnyObject values, it can also store:
because these types are automatically bridged to the corresponding objc types (
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.
Also @rintaro's answer in another good option.