skip to content

In Swift, what are .Type, .self and type(of:), and how does a plug-in registry store types and create instances from them?

level: middleimportance: should knowfreq 40%

answer

  1. the type of a type
  2. postfix self turns a type into a value
  3. dynamic type at run time
  4. init through a metatype needs a guarantee

basics

~20 s

T.Type is the type of the type T, T.self is that type as a value, and type(of:) returns a value's dynamic type. A registry stores metatypes such as any Plugin.Type and creates instances with .init().

solid answer

~40 s

A **metatype** is a type's own type: `ConsoleLogger.Type` is the type of the value `ConsoleLogger.self`. You pass a type as an argument with `.self`, as in `registry.register(ConsoleLogger.self)`, and a generic function receives it as `P.Type`. `type(of: plugin)` returns the **dynamic** metatype, so a value typed `any AnalyticsPlugin` reports `Breadcrumbs` and can reach its static members, such as `type(of: plugin).pluginName`. A registry keeps `[String: any AnalyticsPlugin.Type]` and creates instances with `types[name]?.init()`; the protocol's `init()` requirement makes that legal, and for a class hierarchy the initializer must be `required` (or the class `final`). The `.init` must be explicit: `type(of: x)()` fails with `initializing from a metatype value must reference 'init' explicitly`. Compare metatypes with `==` for an exact type and `is` to include subclasses.

code

swift · 37 lines
swift
protocol AnalyticsPlugin {
    static var pluginName: String { get }
    init()
    func handle(_ event: String)
}

struct ConsoleLogger: AnalyticsPlugin {
    static let pluginName = "console"
    func handle(_ event: String) { print("console:", event) }
}

final class Breadcrumbs: AnalyticsPlugin {
    static let pluginName = "breadcrumbs"
    init() {}
    func handle(_ event: String) { print("breadcrumbs:", event) }
}

struct PluginRegistry {
    private var types: [String: any AnalyticsPlugin.Type] = [:]

    mutating func register<P: AnalyticsPlugin>(_ type: P.Type) {
        types[P.pluginName] = type                  // the metatype is the stored value
    }

    func make(_ name: String) -> (any AnalyticsPlugin)? {
        types[name]?.init()                         // init through the metatype, explicit .init
    }
}

var registry = PluginRegistry()
registry.register(ConsoleLogger.self)               // .self turns the type into a value
registry.register(Breadcrumbs.self)

if let plugin = registry.make("breadcrumbs") {
    plugin.handle("launch")
    print(type(of: plugin), type(of: plugin) == Breadcrumbs.self)   // Breadcrumbs true
}

go deeper

for a junior

Recall that .self turns a type into a value and that type(of:) tells you what a value really is at run time.

for a middle

Explain T.Type parameters, explicit .init through a metatype, and why class initializers called that way must be required.

for a senior

Distinguish concrete, existential and protocol metatypes, and explain why type(of:) inside an unconstrained generic can report the protocol.

for a principal

Weigh a metatype registry against explicit factory closures or a static list, considering discoverability, testability and how plug-ins are registered.

## Types as values Swift lets a program treat a type as a value. Three spellings do the work: | Spelling | Position | Meaning | |---|---|---| | `ConsoleLogger.Type` | type | the **metatype type**, whose value is the type `ConsoleLogger` itself (for a class, also its subclasses) | | `ConsoleLogger.self` | expression | the type `ConsoleLogger` used as a value | | `type(of: value)` | expression | the **dynamic** type of `value`, read at run time | - A bare type name is not a value: `register(ConsoleLogger)` fails with `expected member name or initializer call after type name`, and the compiler suggests `.self`. - A generic parameter's metatype is `T.Type`, so `func register<P: AnalyticsPlugin>(_ type: P.Type)` infers `P` from the argument `ConsoleLogger.self`. - `type(of:)` is resolved specially by the type checker; in non-generic code, for a value whose static type is a superclass or an existential, it returns the concrete type underneath. ## Building a plug-in registry A plug-in registry for an analytics layer needs to remember which types exist and create them later, by name: 1. Declare a protocol with the members the registry needs on the **type**: `static var pluginName: String { get }` and `init()`. 2. Store metatypes in a dictionary keyed by that name: `[String: any AnalyticsPlugin.Type]`. Metatypes are not `Hashable` (`type 'any AnalyticsPlugin.Type' does not conform to protocol 'Hashable'`), so they are the values, not the keys. 3. Register with `registry.register(ConsoleLogger.self)`; inside the generic function, `P.pluginName` reads the static member. 4. Create on demand with `types[name]?.init()`, which returns `(any AnalyticsPlugin)?`. The created value keeps its concrete type, so `type(of: plugin)` prints `Breadcrumbs`, and `type(of: plugin).pluginName` reaches the static property through the dynamic type. ## Creating instances from a metatype Two compiler rules guard initialization through a metatype value: - The call must name `init`: `meta.init()` compiles, while `meta()` fails with `initializing from a metatype value must reference 'init' explicitly`. - For classes, the initializer must exist on every subclass. With `let m: Base.Type = Sub.self`, calling `m.init()` on a non-required initializer fails with `constructing an object of class type 'Base' with a metatype value must use a 'required' initializer`. Mark the initializer `required`, or the class `final`. A protocol `init()` requirement satisfies the same need for an existential metatype: every conformer must provide it, and a non-final class conformer must mark it `required`. ## Concrete, existential and protocol metatypes | Spelling | Holds | Example value | |---|---|---| | `Breadcrumbs.Type` | the class and its subclasses | `Breadcrumbs.self` | | `any AnalyticsPlugin.Type` | the metatype of any conforming type | `ConsoleLogger.self` | | `(any AnalyticsPlugin).Type` | only the protocol type itself | `(any AnalyticsPlugin).self` | The last row is the **protocol metatype**, which the book still calls `AnalyticsPlugin.Protocol`. It is not a conformer's type, so `let m: any AnalyticsPlugin.Type = AnalyticsPlugin.self` fails with `cannot convert value of type '(any AnalyticsPlugin).Type' to specified type 'any AnalyticsPlugin.Type'`. SE-0335 introduced these `any` spellings in Swift 5.6. ## Where metatypes appear in everyday Swift The registry is the deliberate use, but metatypes show up in APIs every Swift developer calls: - `JSONDecoder().decode(User.self, from: data)` takes the target type as `T.Type`, because there is no value to infer `T` from. - `withTaskGroup(of: Int.self) { … }` names the child task result type the same way. - `String(describing: type(of: event))` produces a type name for a log line, for example `PurchaseEvent`. - `[Any.Type]` holds a list of arbitrary types, for example the types a test should exercise. ## Comparing and casting metatypes - `type(of: x) == Base.self` is true only for an exact match; the standard library's `==` on metatypes compares type identity. - `x is Base` and `meta is Base.Type` also accept subclasses. - `meta as? ConsoleLogger.Type` downcasts a metatype like any other value. ## Common mistakes - Passing a type without `.self`, or passing an instance where a metatype is expected. - Calling `meta()` instead of `meta.init()`. - Forgetting `required` on a class initializer that the registry calls through a metatype. - Trying to key a dictionary by metatype instead of by a stable name. - Confusing `any P.Type` with the protocol metatype `(any P).Type`.

  • Inside func describe<T>(_ value: T), why can type(of: value) print the protocol name instead of the concrete type?
    When the caller passes an `any AnalyticsPlugin`, an unconstrained `T` is bound to the existential type itself, and `type(of:)` must return a `T.Type`, which is the protocol metatype. The standard library's documentation for `type(of:)` recommends `type(of: value as Any)` there; that returns the concrete type, such as `ConsoleLogger`.
  • When would you take a T.Type parameter instead of inferring T from a value?
    When the function has no value of that type to infer from: creating instances, decoding (`decode(_:from:)` takes the target type as a metatype), or looking something up by type. The explicit `ConsoleLogger.self` at the call site names the type the caller wants.

  • You can pass a type to a function by writing its bare name.
  • type(of:) returns the declared static type of the variable.
  • A metatype can be called directly like a function to create an instance.
  • AnalyticsPlugin.self is a value of type any AnalyticsPlugin.Type.
  • type(of: x) == Base.self is true for subclass instances.