3

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?

Yonguk Jeong
  • 258
  • 1
  • 6
  • 7
    See [Why can't I pass a Protocol.Type to a generic T.Type parameter?](https://stackoverflow.com/q/45234233/2976878) – for `foo(Any.self)`, `Any.self` is treated as `Any.Protocol` allowing the code to compile. – Hamish Mar 25 '19 at 13:29
  • @Hamish Thank you for the link! It really helped me understand how it works. – Yonguk Jeong Mar 26 '19 at 10:26

0 Answers0