【问题标题】:what is T.Type in swiftswift中的T.Type是什么
【发布时间】:2018-05-29 21:35:47
【问题描述】:

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

我认为这是对我编码的数据进行解码的类型。

很多例子都是这样使用上述方法的:

JSONEncoder().decode([People].self, from: data)

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

我知道泛型,但T.Type 是什么?

TT.Type 之间有什么区别?

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

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

T.TypeType.self 到底是什么?

【问题讨论】:

标签: swift generics types


【解决方案1】:
  • 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 someValue: Int中,具体的符号identifier: Type(在本例中为someValue: Int意味着 someValue 将是一个实例诠释。如果您希望 someValue 是对实际类型 Int 的引用,您可以编写 var someValue: Int.Type = Int.self 请记住,.Type 表示法仅在向编译器声明类型和类型签名时使用,.self 属性在实际中使用在执行时检索对类型对象本身的引用的代码。

  • JSONDecoder().decode 需要T.Type 的参数(其中T 符合Decodable)的原因是因为任何符合Decodable类型 都有一个初始化器init(from decoder: Decoder)decode 方法需要在符合Decodable类型 上调用此init 方法,而不是在符合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"
    

【讨论】:

猜你喜欢
  • 2020-08-20
  • 2022-11-17
  • 1970-01-01
  • 2019-08-20
  • 2014-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-23
相关资源
最近更新 更多