谁能告诉我什么是T.Type
当我使用JSONDecoder().decode()
?
我认为它是解码我编码的数据的类型。
很多例子都使用上面的方法,如下所示:
JSONEncoder().decode([People].self, from: data)
如果我检查该方法的定义我可以看到T.Type
.
我知道泛型但什么是T.Type
?
只是有什么区别T
and T.Type
?
当我们声明一些变量时,我们像这样分配它们的类型
var someValue: Int
, not var someValue: Int.self
是什么T.Type
完全并且Type.self
?
-
T.Type
用于参数和约束中,表示“事物本身的类型,而不是事物的实例”。
例如:
class Example {
static var staticVar: String { return "Foo" }
var instanceVar: String { return "Bar" }
}
func printVar(from example: Example) {
print(example.instanceVar) // "Bar"
print(example.staticVar) // Doesn't compile, _Instances_ of Example don't have the property "staticVar"
}
func printVar(from example: Example.Type) {
print(example.instanceVar) // Doesn't compile, the _Type_ Example doesn't have the property "instanceVar"
print(example.staticVar) // prints "Foo"
}
您将获得对 Type 的引用.Type
(类型对象本身)在运行时通过致电TheType.self
。语法TheType.Type
在类型声明和类型签名中使用仅向编译器指示实例与类型的区别。例如,您实际上无法获得参考,Int
在运行时或通过调用在函数实现中的类型Int.Type
。你会打电话Int.self
在示例代码中var someValue: Int
,具体记号identifier: Type
(在这种情况下,someValue: Int
) meanssomeValue 将是instance的国际。如果您希望 someValue 成为对实际类型 Int 的引用,您可以编写var someValue: Int.Type = Int.self
请记住,.Type
表示法仅在向编译器声明类型和类型签名时使用,并且.self
属性在实际代码中用于在执行时检索对类型对象本身的引用。
-
之所以JSONDecoder().decode
需要一个参数T.Type
(where T
符合Decodable
)是因为任何type符合Decodable
有一个初始化程序init(from decoder: Decoder)
. The decode
方法将需要调用此 init 方法type符合Decodable
,不在instance的类型符合Decodable
。例如:
var someString: String = ""
someString.init(describing: 5) // Not possible, doesn't compile. Can't call an initializer on an _instance_ of String
var someStringType: String.Type = String.self
someStringType.init(describing: 5) // Iniitializes a String instance "5"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)