2

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?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
iOSDev
  • 326
  • 2
  • 10

1 Answers1

3

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.

Cristik
  • 30,989
  • 25
  • 91
  • 127
  • I know _"Int's become NSNumber, array's become NSArray"_ Thanks for explaining the _Swift-only values_ thing – iOSDev Sep 03 '19 at 02:25