Search code examples
swiftanyobject

Why casting function type as AnyObject works


Question : Difference between Any vs. AnyObject

Answer : Any can represent an instance of any type at all, including function types and optional types.

AnyObject can represent an instance of any class type.

I tried to store a function type in a Any and a AnyObject variables

func add(a: Int, b: Int) -> Int {
    return a + b
}
let funcType = add
let test1: Any = funcType
let test2: AnyObject = funcType//Value of type '(Int, Int) -> Int' does not conform to specified type 'AnyObject' Insert ' as AnyObject'

When I use the fix option

let test2: AnyObject = funcType as AnyObject

It works without any error. How am I able to store a function type in a AnyObject?


Solution

  • Behind the scenes as AnyObject converts the casted value to an Objective-C compatible one: Int's become NSNumber, array's become NSArray, and so on. Swift-only values get wrapped within opaque SwiftValue instances.

    print(type(of: test2)) // __SwiftValue
    

    This is why adding as AnyObject makes your code compile, as the right-hand of the operator is now an object.