Behavior of Swift Any.Type and generics

169 Views Asked by At

Given a function with a generic parameter, I would like to pass a value of which type is Any.Type to the function but it doesn't compile.

func foo<T>(_ type: T.Type) {
    print(type)
}

foo(Any.self) // ok
foo(Int.self) // ok

let a: Any.Type = Any.self // ok
let b: Any.Type = Int.self // ok

foo(a) // error: expected an argument list of type '(T.Type)'
foo(b) // error: expected an argument list of type '(T.Type)'

My assumption is that:

  1. foo(Any.self) successfully compiles and the type placeholder T would hold Any.

  2. Similarly, if a value of type Any.Type is given, the T should be resolved into Any

Could you explain why this code doesn't work?

0

There are 0 best solutions below