Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Metatypes in Swift
Written by Team Kodeco

A meta type in Swift refers to the type that describes the type itself. The meta type of a class, structure, enumeration or protocol is written with a dot (.) followed by the keyword self. For example, the meta type of the class Vehicle would be Vehicle.self.

class Car {
  required init() {}
  func start() {
    print("Starting car")
  }
}

let metaType = Car.self

In this code, you define a class Car with a method start() that prints “Starting car” when called.

Next, you create a constant metaType that’s set to the meta type of Car using Car.self. The meta type of a class is a type that describes the class itself.

You can use the meta type to dynamically create instances of the class, access type-level properties and methods, and perform other type-related operations.

let instance = metaType.init()
instance.start() // Output: Starting car

Using Meta Types with Protocols

Here’s an example of using the meta type to access functions defined in a protocol:

protocol Vehicle {
  init()
  func start()
}

class Car: Vehicle {
  required init() {}
  func start() {
    print("Starting car")
  }
}

let metaType: Vehicle.Type = Car.self

// Create an instance of the class using the meta type
let carInstance = metaType.init()

// Call the start() method of the instance
carInstance.start()   // Output: Starting car

In this code, you add an init() method to the Vehicle protocol, and Car implements it with the required keyword to indicate that it must be implemented by any class that conforms to the protocol.

Next, you create a constant metaType that is set to the meta type of Car, but you specify its type as Vehicle.Type. This allows you to access only the functions defined in the Vehicle protocol, not the functions defined in Car.

Finally, you create an instance of Car using the meta type by calling init() on the metaType and call the start() on the new instance.

Meta types are a way to access the type of a class, structure or enumeration in Swift. The meta type is a type that represents the type of the class, structure or enumeration. It can be used to create instances of the type, access its properties and call its methods. Meta types are a feature of the Swift language and aren’t tied to any particular framework.

© 2024 Kodeco Inc.