Swift Any.Type和泛型的行为

时间:2019-03-25 13:20:36

标签: swift generics metatype

给出具有泛型参数的函数,我想将类型为Any.Type的值传递给该函数,但它不会编译。

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)'

我的假设是:

  1. foo(Any.self)成功编译,类型占位符T将容纳Any

  2. 类似地,如果给出类型为Any.Type的值,则T应该解析为Any

您能解释一下为什么这段代码不起作用吗?

0 个答案:

没有答案