0
這個問題從各地NSKeyedUnarchiver
閱讀文檔起源(文檔here)和它的下面實例方法:爲什麼要傳遞一個通用的類型時,它已經知道
func decodeDecodable<T>(_ type: T.Type, forKey key: String) -> T? where T : Decodable
什麼是_ type: T.Type
路過的時候該類型的目的已經可以從T
確定?
這個問題從各地NSKeyedUnarchiver
閱讀文檔起源(文檔here)和它的下面實例方法:爲什麼要傳遞一個通用的類型時,它已經知道
func decodeDecodable<T>(_ type: T.Type, forKey key: String) -> T? where T : Decodable
什麼是_ type: T.Type
路過的時候該類型的目的已經可以從T
確定?
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