swift中的T.Type是什么

Don*_*Lee 6 generics types swift

谁能告诉我什么T.Type时候我使用JSONDecoder().decode()?

我认为它是解码我编码的数据的类型

这么多的例子使用上面这样的方法

JSONEncoder().decode([People].self, from: data) ...
Run Code Online (Sandbox Code Playgroud)

如果我检查该方法的定义,我可以看到T.Type.

我知道仿制药但是什么 T.Type

只有T和T.Type有什么区别

当我们声明一些变量时,我们就像这样分配它们的类型

var someValue: Int 不是 var someValue: Int.self

什么是T.Type确切的和Type.self

Dan*_*all 16

  • 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"
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • 您可以通过调用在运行时获得对Type .Type(Type对象本身)的引用.语法仅在类型声明和类型签名中使用,以向编译器指示实例与类型的区别.实际上,您无法通过调用获得对运行时或函数实现中的类型的引用.你会打电话TheType.selfTheType.TypeIntInt.TypeInt.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(from decoder: Decoder).该decode方法需要在符合的类型上调用此init方法Decodable,而不是在符合的类型的实例上调用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"
    
    Run Code Online (Sandbox Code Playgroud)

  • 感谢您的详细信息和出色的回答! (2认同)