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

swift – 元类型的元类型

发布时间:2020-12-14 05:58:49 所属栏目:百科 来源:网络整理
导读:在Swift中我们可以写下如下的结构: class SomeClass {}let metaMetatype: SomeClass.Type.Type = SomeClass.Type.self 这里的metaMetatype不符合类型AnyObject(SomeClass.Type)。施工可以更长,只要我们希望: let uberMetatype: SomeClass.Type.Type.Type.
在Swift中我们可以写下如下的结构:
class SomeClass {}
let metaMetatype: SomeClass.Type.Type = SomeClass.Type.self

这里的metaMetatype不符合类型AnyObject(SomeClass.Type)。施工可以更长,只要我们希望:

let uberMetatype: SomeClass.Type.Type.Type.Type.Type.Type.Type.Type.Type.Type = SomeClass.Type.Type.Type.Type.Type.Type.Type.Type.Type.self

这个结构有什么意义吗?如果SomeClass.Type.Type不是一个对象,这是什么,为什么我们能够声明它?

If SomeClass.Type.Type not an object,what is this and why we able to declare it?

我会试图剖析你问的是什么。

SomeClass.Type.Type是元类型的元类型。元类型存在于Swift中,因为Swift具有不是类的类型。这最类似于Objective-C中的元类概念。

Lexicon.rst在Swift中的开源Repo有一个很好的解释:

metatype

The type of a value representing a type. Greg Parker has a good
explanation of 07001 because Swift has types
that are not classes,a more general term is used.

We also sometimes refer to a value representing a type as a “metatype
object” or just “metatype”,usually within low-level contexts like IRGen
and LLDB. This is technically incorrect (it’s just a “type object”),but
the malapropism happened early in the project and has stuck around.

为什么我们能够声明一个类型的类型…等等?因为它是称为类型元数据的语言的一个特性:

type metadata

The runtime representation of a type,and everything you can do with it.
Like a Class in Objective-C,but for any type.

注意,你不能像Swift中的NSObject()。类一样做,因为类是创建类的保留关键字。这是你将如何获得一个NSObject的类型(在这种情况下的类)在Swift:

let nsObj = NSObject()
nsObj.classForCoder // NSObject.Type
nsObj.classForKeyedArchiver // NSObject.Type
nsObj.dynamicType // NSObject.Type

注意,nsObj和nsObj.self是相同的,并且表示该NSObject的实例。

我看不到在Swift模块或开源代码在哪里类型允许.Type,但我仍然在寻找。它可能与SwiftObject的继承,Objective-C对象所有Swift类继承(至少在Mac上)。

(编辑:李大同)

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

    推荐文章
      热点阅读