当我使用JSONDecoder()。decode()时,有人能告诉我T.Type
是什么吗?
我认为解码数据的类型
这么多的例子使用上面这样的方法
JSONEncoder().decode([People].self, from: data) ...
如果我检查该方法的定义,我可以看到T.Type
。
我知道泛型,但是T.Type
T和T.Type
之间的区别是什么当我们声明一些变量时,我们就像这样分配了它们的类型
var someValue: Int
,而不是var someValue: Int.self
T.Type
究竟是什么,Type.self
答案 0 :(得分:15)
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
(Type对象本身)的引用。语法TheType.Type
仅用于类型声明和类型签名,以向编译器指示实例与类型的区别。实际上,您无法通过调用Int
在运行时或函数实现中获得对Int.Type
类型的引用。您可以致电Int.self
在示例代码var someValue: Int
中,特定符号identifier: Type
(在本例中为someValue: Int
)表示 someValue将是实例的Int。如果你想someValue是对实际类型Int的引用,你会写var someValue: Int.Type = Int.self
请记住.Type
符号仅在向编译器声明类型和类型签名时使用{{1}在实际代码中使用property来在执行时检索对类型对象本身的引用。
.self
要求参数JSONDecoder().decode
(其中T.Type
符合T
)的原因是因为任何类型符合到Decodable
有一个初始值设定项Decodable
。 init(from decoder: Decoder)
方法需要在符合decode
的类型上调用此init方法,而不是符合类型的实例 Decodable
。例如:
Decodable