这个问题源于阅读关于 NSKeyedUnarchiver
的文档(文档 here )及其下面的实例方法:
func decodeDecodable<T>(_ type: T.Type, forKey key: String) -> T? where T : Decodable
当已经可以从 T
确定类型时,传入 _type: T.Type
的目的是什么?
最佳答案
Swift 只允许您在类型上显式指定泛型参数,而不是在方法或函数上。
struct Foo<T> {
func bar<U>() -> U
}
let foo = Foo<Int>() // legal
foo.bar<Int>() // illegal
语言可以从返回值推断出T
:
let foo = Foo<Int>() // legal
let bar: Int = foo.bar() // legal: T inferred to be Int
然而,这在使用多态性时并不总是正确的。
class Bar {}
class Baz: Bar {}
let decoded: Bar = decodeDecodable(forKey: "baz")
// would infer decodeDecodable<Bar>(forKey: "baz")
// which is not correct for a Baz object
关于swift - 为什么在泛型类型已知时传入它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46574931/