Metatypes in Swift

Why .self and .type matter

Steven Curtis
5 min readApr 3, 2023
Photo by Jake Hills on Unsplash

Before we start

Difficulty: Beginner | Easy | Normal | Challenging

Keywords and Terminology:

Metatypes: the type of any type

Prerequisites:

  • None

Why

In Swift, you might have noticed that some code uses .self and some uses .type for various uses which can seem rather opaque to the beginner.

These are useful, and should not simply be ignored however!

A Simple example

You might have a rather forced example as follows:

struct Person{
var name: String
init(_ name: String) {
self.name = name
}
}

let tina = Person("Tina")

so tina is clearly an instance of Person.

We can see this with the following print statements:

print(tina.self) // Person(name: "Tina")
print(type(of: tina)) // Person

The overview

Each instance of Person can be represented by two things, the Type of the metatype.

Type: Person
Metatype: Person.Type

--

--