swift中的T.类型是什么
当我使用swift中的T.类型是什么,swift,generics,types,Swift,Generics,Types,当我使用JSONDecoder().decode()时,谁能告诉我什么是T.Type 我认为这是一种对我编码的数据进行解码的类型 许多示例使用上述方法,如下所示: JSONEncoder().decode([People].self, from: data) 如果我检查该方法的定义,我可以看到T.Type 我知道泛型,但什么是T.Type 仅仅T和T.Type之间有什么区别 当我们声明一些变量时,我们像这样分配它们的类型 var someValue:Int ,而不是var someValue:
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
?
在参数和约束中用于表示“事物本身的类型,而不是事物的实例” 例如: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" }
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"
- 通过调用
,可以在运行时获得对类型的Type.self
(类型对象本身)的引用。语法.Type
仅用于类型声明和类型签名中,以向编译器指示实例与类型的区别。例如,在运行时或在函数实现中调用Type.Type
,实际上无法获取对Int.type
类型的引用。您可以调用Int
Int.self
- 在示例代码
中,特定符号var-someValue:Int
(在本例中,identifier:Type
)表示someValue将是Int的一个实例。如果希望someValue是对实际Int类型的引用,您可以编写someValue:Int
记住,var someValue:Int.Type=Int.self
符号仅在向编译器声明类型和类型签名时使用,而.Type
属性在实际代码中用于在执行时检索对类型对象本身的引用.self
要求参数JSONDecoder().decode
(其中T.Type
符合T
)的原因是符合Decodable
的任何类型都有一个初始值设定项Decodable
。init(来自解码器:decoder)
方法需要在符合decode
的类型上调用此init方法,而不是在符合Decodable
的类型实例上调用此init方法。例如:Decodable
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" }
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"
T.Type
是T
的最新版本。感谢您提供的详细信息和极好的回答!通过谷歌搜索“Swift Metatype”可以找到相关的苹果文档,这应该会让你找到:。极好的答案很好的答案!!非常感谢。