Learn about MetaType in Swift

Tram Ho


In Swift, if Type is literally translated as the type of a variable, then MetaType is the type of the variable type. For example, the number 5 has a type of Int , or an Int variable can receive a value of 5. However, to write a method that returns the amount of memory that a variable type occupies, we cannot pass on the price. The value of the variable that needs to pass the type of the variable type: MetaType .

.Type and .self

In the Swift language, MetaType is denoted via the .Type property. Each variable can be of value: if an Int type variable can have a value of 5, then the value of an Int type variable can have a value expressed by the .self attribute. For example, Int.Type is a type of Int type, carrying the value Int.self .


Static properties and methods can be accessed and used after obtaining the MetaType . In fact, we often use MetaType , for example a very popular method of UITableView :

Here, AnyClass actually a MetaType :

When we access the static property, we actually access it via MetaType , but XCode cleverly hides it by omitting .self . The following two ways of writing are equivalent:

type(of:) and .self

We can all use type(of:) and .self to get the value for MetaType :

The difference is that the type(of:) function is called on the variable, while .self is called on the variable’s type.


Protocol is not a type in Swift, so it is not possible to directly access the value of Protocol’s type via .self but through a class or struct compatible with that Protocol:

So what does .self on Protocol mean? That is the value of Protocol’s Protocol type:

For example

Suppose we have two different classes that share the same protocol. We need to write an object initializer function based on the type of the class.

The constructor function can be written in a direct manner MetaType :

Or you can write using generics:

The Reusable library uses the same way for the dequeueReusableCell method:



Share the news now

Source : Viblo