Types and meta types in swift

Knowing the types andmeta-types in swift is not as important as in Objc. Where in objective c, you can instantiate an object out of a class name or modify classes at runtime, it’s not possible in pure swift.

了解swift中的类型和元类型并不像Objc那么重要。 在oc中,您可以在类名中实例化对象或在运行时修改类,在纯swift中是不可能的。

The fact that swift is a language that supports generics, and has little to no reflection capabilities, knowing and dealing with types and meta-types is not a very common task.

事实上swift是一种支持泛型的语言,几乎没有反射功能,知道和处理类型和元类型并不是一个非常常见的任务。

However, there are times when you need to know what type your instances (or classes) are. In that area, swift provides two ways of getting the types; calling type(of: ) on an instance, or .self on a Class/Structure.

但是,有时您需要知道实例(或类)的类型。 在那个领域,swift提供了两种获取类型的方法; 在实例上调用type(of: ),或在类/结构上调用.self。

Type.self

The meta type of a type can be found by calling .self on a type. The returned type can either be a Class meta-type, a Struct meta-type or a Protocol meta-type.

可以通过在类型上调用.self来找到类型的元类型。 返回的类型可以是Class元类型,Struct元类型或Protocol元类型。


image.png

image.png

Even if the above look similar, they act different. The type return from calling NSString.self looks similar to an Objective C class. ”

即使上面看起来相似,它们的行为也不同。 调用NSString.self的类型返回类似于Objective C类

The object returned from calling MyClass.self is the swift metaType of MyClass. This object exposes init function and all the method defined in this class as curried method (read Instance Methods are Curried Functions in Swift).

从调用* MyClass.self 返回的对象是MyClass的swift元类型。 此对象将 init *函数和此类中定义的所有方法公开为curried方法

If we pass MyClass.self to NSStringFromClass we get the mangled class name.

如果我们将MyClass.self传递给NSStringFromClass,我们会得到错位的类名。

String.self returns a similar to calling self on a swift class. A difference to note here, if we pass it to NSStringFromClass we get a compilation error. This should not be surprising as string is a struct and not a class.

String.self返回一个类似于在swift类上调用self的方法。 这里要注意的区别是,如果我们将它传递给NSStringFromClass,我们会得到一个编译错误。 这不应该是令人惊讶的,因为字符串是结构而不是类。

type(of: )

If .self is used on a Type to returns its metatype, type(of: ) is used on an instance to return its metatype. The type returned is the same returned when calling .self on the instance static type.

如果在类型上使用.self返回其元类型,则在实例上使用type(of: )来返回其类型。 返回的类型与在实例静态类型上调用.self时返回的相同。

Comparing the dynamic type to the static type for most of the struct and types; we can compare instances of String as follows:

将动态类型与大多数结构和类型的静态类型进行比较; 我们可以比较String的实例如下:


image.png

Comparing types directly is considered bad practice and is discouraged. The safe swift way to correctly check the type of an instance we must swift’s is statement. To compare the doubles from above we would use (please ignore swift warning us that the result is always true)

直接比较类型被认为是不好的做法,并且不鼓励。 正确检查实例类型的安全快捷方式是使用 swift 的 is 语句。

image.png

We can create a new instance from a type. For example to create an instance from MyClass we can use the following:

我们可以从一个类型创建一个新实例。 例如,要从MyClass创建实例,我们可以使用以下内容:


image.png

image.png

Holding a metatype references

When storing the result of type(of: "") or String.self to a variable, the inferred type is String.Type, String.Type can so be used to annotate meta type variables:

type(of:""String.self的结果存储到变量时,推断的类型是String.Type,String.Type可用于注释元类型变量:

Variable annotated with String.Type or any Struct.Type can only store that struct meta-type. The compiler won’t allow us to store another metatype to the same variable:

使用String.Type或任何Struct.Type注释的变量只能存储该struct meta-type。 编译器不允许我们将另一个元类型存储到同一个变量中:


image.png

For classes, since they can be subclassed, the behaviour is different. A BaseClass.Type can also hold references of SubClass.Type.

对于类,因为它们可以被子类化,所以行为是不同的。 BaseClass.Type也可以包含SubClass.Type的引用。

Bellow we store NSDictionary.self and NSMutableDictionary.self to the same variable:

Bellow我们将NSDictionary.self和NSMutableDictionary.self存储到同一个变量中:


image.png

Note that the opposite won’t work, if we annotated the type with NSMutableDictionary.Type the compiler won’t allow us to store a reference of NSDictionary.self.

请注意,相反的方法不起作用,如果我们用NSMutableDictionary.Type注释类型,编译器将不允许我们存储NSDictionary.self的引用。


image.png

A Protocol.Type variable, unsurprisingly, can hold a reference to any type thats implementing that protocol:

不出所料,Protocol.Type变量可以包含对实现该协议的任何类型的引用:


image.png

To note here, only protocols that don’t have associated type or Self requirements can be used to annotate variables. Protocols that have Self or associated type requirements can only use as generic constraints.

此处需要注意的是,只有没有关联类型或自我要求的协议才能用于注释变量。 具有Self或关联类型要求的协议只能用作通用约束。


image.png

As a final note, variables annotated with Any.Type can well, hold any type, whether the type is a structure or a class.

最后要注意的是,使用Any.Type注释的变量可以很好地保存任何类型,无论类型是结构还是类。


image.png
image.png
image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,907评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,987评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,298评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,586评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,633评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,488评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,275评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,176评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,619评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,819评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,932评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,655评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,265评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,871评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,994评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,095评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,884评论 2 354

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,331评论 0 10
  • 近日众安保险上市消息传开,据优米了解,众安保险为了上市在亏损状态下也要加持上市,原因究竟是什么,今日优米带您了解一...
    farfar阅读 337评论 0 0
  • 夜落风来波澜劲, 雨敲寒窗梦几回。 露芽未发寒又至, 待到东风又几时。
    莫微阅读 173评论 0 2
  • 几年前梦想在深圳大芬有个属于自己的工作室,反而在海南老家拥有了理想中的画室,梦想与现实之间的差别。 从一棵好奇之心...
    默孔阅读 430评论 2 1
  • 现在大部分人只愿意碎片化学习,听自己愿意听的,看自己愿意看的,然后草率得出结论。我从来就不相信什么读书无用论,...
    胡争争阅读 361评论 0 0