加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift中的T.Type是什么

发布时间:2020-12-14 05:39:28 所属栏目:百科 来源:网络整理
导读:当我使用 JSONDecoder().decode()时,谁能告诉我什么是T.Type? 我认为它是解码我编码的数据的类型 这么多的例子使用上面这样的方法 JSONEncoder().decode([People].self,from: data) ... 如果我检查该方法的定义,我可以看到T.Type. 我知道泛型,但什么是T.Typ
当我使用 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"
}

>通过调用TheType.self,您可以在运行时获得Type的.Type(Type对象本身)的引用.语法TheType.Type用于类型声明和类型签名,仅用于向编译器指示实例与类型的区别.实际上,您无法通过调用Int.Type来获取对运行时或函数实现中的Int类型的引用.你会打电话给Int.self
>在示例代码var someValue:Int中,特定符号标识符:Type(在本例中为someValue:Int)表示someValue将是Int的实例.如果你想someValue是对实际类型Int的引用,你可以写var someValue:Int.Type = Int.self请记住.Type表示法仅用于向编译器声明类型和类型签名,以及.self property在实际代码中用于在执行时检索对类型对象本身的引用.
> JSONDecoder().decode需要T.Type参数(其中T符合Decodable)的原因是因为任何符合Decodable的类型都有一个初始化器init(来自解码器:解码器). 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"

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读