元類型是指所有類型的類型。
元類型只能類型出現在類型標示位;
類型即能作為類型存在,出現在類型標示位;
也能作為變量存在,出現在元類型的變量位。
?
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