swift中的T.Type是什么
当我使用
JSONDecoder().decode()时,谁能告诉我什么是T.Type?
我认为它是解码我编码的数据的类型 这么多的例子使用上面这样的方法 JSONEncoder().decode([People].self,from: data) ... 如果我检查该方法的定义,我可以看到T.Type. 我知道泛型,但什么是T.Type 只有T和T.Type有什么区别 当我们声明一些变量时,我们就像这样分配它们的类型 var someValue:Int 什么是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" } >通过调用TheType.self,您可以在运行时获得Type的.Type(Type对象本身)的引用.语法TheType.Type用于类型声明和类型签名,仅用于向编译器指示实例与类型的区别.实际上,您无法通过调用Int.Type来获取对运行时或函数实现中的Int类型的引用.你会打电话给Int.self 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" (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |