元类型与类型的区别

元类型是指所有类型的类型。

元类型只能类型出现在类型标示位;

类型即能作为类型存在,出现在类型标示位;

也能作为变量存在,出现在元类型的变量位。

 

http://www.swift51.com/swift2.0/chapter3/03_Types.html#type_inheritance_clause

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Types.html#//apple_ref/swift/grammar/metatype-type

A metatype type refers to the type of any type, including class types, structure types, enumeration types, and protocol types.

The metatype of a class, structure, or enumeration type is the name of that type followed by .Type. The metatype of a protocol type—not the concrete type that conforms to the protocol at runtime—is the name of that protocol followed by .Protocol. For example, the metatype of the class type SomeClass is SomeClass.Type and the metatype of the protocol SomeProtocol is SomeProtocol.Protocol.

You can use the postfix self expression to access a type as a value. For example, SomeClass.self returns SomeClass itself, not an instance of SomeClass. And SomeProtocol.self returns SomeProtocol itself, not an instance of a type that conforms to SomeProtocol at runtime. You can call the type(of:) function with an instance of a type to access that instance’s dynamic, runtime type as a value, as the following example shows:

元类型

元类型是指所有类型的类型,包括类、结构体、枚举和协议。

类、结构体或枚举类型的元类型是相应的类型名紧跟.Type。协议类型的元类型——并不是运行时遵循该协议的具体类型——是该协议名字紧跟.Protocol。比如,类SomeClass的元类型就是SomeClass.Type,协议SomeProtocol的元类型就是SomeProtocal.Protocol

你可以使用后缀self表达式来获取类型。比如,SomeClass.self返回SomeClass本身,而不是SomeClass的一个实例。同样,SomeProtocol.self返回SomeProtocol本身,而不是运行时遵循SomeProtocol的某个类型的实例。还可以对类型的实例使用dynamicType表达式来获取该实例在运行阶段的类型,如下所示:

可以使用恒等运算符(===和 !==)来测试一个实例的运行时类型和它的编译时类型是否一致。

可以使用初始化表达式从某个类型的元类型构造出一个该类型的实例。对于类实例,必须使用 required关键字标记被调用的构造器,或者使用 final 关键字标记整个类。

元(Metatype)类型语法
元类型 → 类型 . Type | 类型 . Protocol

posted @ 2018-05-29 18:31  zzfx  阅读(322)  评论(0编辑  收藏  举报