Swift 为什么要传入一个通用的';当它';他已经知道了
这个问题源于阅读有关Swift 为什么要传入一个通用的';当它';他已经知道了,swift,generics,swift4,Swift,Generics,Swift4,这个问题源于阅读有关NSKeyedUnarchiver(文档)的文档及其下面的实例方法: func decodeDecodable<T>(_ type: T.Type, forKey key: String) -> T? where T : Decodable func可解码(uuType:T.type,forKey:String)->T?其中T:可解码 当类型已经可以通过T确定时,传入\utype:T.type的目的是什么?Swift只允许您在类型上明确指定泛型参数,而
NSKeyedUnarchiver
(文档)的文档及其下面的实例方法:
func decodeDecodable<T>(_ type: T.Type, forKey key: String) -> T? where T : Decodable
func可解码(uuType:T.type,forKey:String)->T?其中T:可解码
当类型已经可以通过
T
确定时,传入\utype:T.type
的目的是什么?Swift只允许您在类型上明确指定泛型参数,而不是在方法或函数上
struct Foo<T> {
func bar<U>() -> U
}
let foo = Foo<Int>() // legal
foo.bar<Int>() // illegal
但是,在使用多态性时,这并不总是正确的
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
类栏{}
类Baz:Bar{}
let decoded:Bar=可解码(forKey:“baz”)
//将推断可解码(forKey:“baz”)
//这对于Baz对象是不正确的
Swift仅允许您在类型上明确指定泛型参数,而不是在方法或函数上
struct Foo<T> {
func bar<U>() -> U
}
let foo = Foo<Int>() // legal
foo.bar<Int>() // illegal
但是,在使用多态性时,这并不总是正确的
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
类栏{}
类Baz:Bar{}
let decoded:Bar=可解码(forKey:“baz”)
//将推断可解码(forKey:“baz”)
//这对于Baz对象是不正确的