2017-10-04 35 views

回答

3

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 
相關問題