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