Metatype

// metatype of a (class, struct, enum) type
SomeType.Type

// metatype of a protocol
SomeProtocol.Type

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

  • The dynamic type (runtime type) returned from type(of:) is a concrete metatype (T.Type) for a class, struct, enum, or other nonprotocol type T, or an existential metatype (P.Type) for a protocol or protocol composition P. 👉 1️2️

  • When the static type (compile-time type) of the value passed to type(of:) is constrained to a class or protocol, you can use that metatype to access initializers or other static members of the class or protocol. 👉 1️3️

  • Use an initializer expression to construct an instance of a type from that type’s metatype value. 👉 3️4️

  • For class instances, the initializer that’s called must be marked with required or the entire class marked with final. 👉4️ (the compiler must make sure the initializer is implemented by every possible subtype of the type)

Last updated

Was this helpful?