skip to content

In a Swift protocol, what does capital `Self` mean in a requirement such as `func copy() -> Self`?

level: juniorimportance: should knowfreq 45%

answer

  1. the type that adopts it
  2. not the protocol, not the instance
  3. Equatable's two operands
  4. non-final classes are the trap

basics

~20 s

In a protocol, Self stands for the eventual conforming type: func copy() -> Self obliges a struct Draft to return a Draft, not just any conforming value. Lowercase self is the instance; a non-final class must write the return type as Self.

solid answer

~40 s

Inside a protocol, `Self` is a placeholder for whatever type eventually conforms: The Swift Programming Language calls it "the eventual type that conforms to the protocol". So `func copy() -> Self` is satisfied in a struct `Draft` by `func copy() -> Draft`, and `Equatable`'s `==` takes two values of that one type, which is why it never compares an `Int` with a `String`. Lowercase `self` is the current instance; `Self` is its type. The trap is a non-final class: every subclass inherits the conformance, so the class must declare `-> Self`, and creating a fresh instance then means calling `Self(...)` through a `required` initializer so each subclass gets back its own type.

code

swift · 19 lines
swift
protocol Duplicable {
    func copy() -> Self
}

struct Draft: Duplicable {
    var title: String
    func copy() -> Draft { self }   // in a struct, Self is simply Draft
}

class Document: Duplicable {
    var title: String
    required init(title: String) { self.title = title }
    func copy() -> Self { Self(title: title) }
}

final class Invoice: Document {}

let doc: Document = Invoice(title: "Q3")
print(type(of: doc.copy()))   // Prints "Invoice"

go deeper

for a junior

Recall that Self means the conforming type and self means the instance, and show a struct satisfying a copy() -> Self requirement by returning its own type.

for a middle

Explain why Equatable's operands are both Self and what that rules out, and why a non-final class must return Self rather than its class name.

for a senior

Walk through the required-initializer chain behind Self(...) in a class hierarchy, and show that a copy taken through a base-class variable keeps the subclass type.

for a principal

Weigh where a Self requirement earns its keep in a shared protocol against the restrictions it places on every class hierarchy and existential that adopts it.

## What `Self` refers to In Swift, capital **`Self`** is not a specific type. It is a way to name *the current type* without spelling it. Its meaning depends on where it appears: - In a **protocol** declaration or a protocol member, `Self` refers to the eventual type that conforms to the protocol. - In a **struct, enum or class** declaration, `Self` refers to the type that declaration introduces. - In a class, `Self` is the **dynamic** type of the instance, the same type `type(of: self)` returns, which can be a subclass. Lowercase **`self`** is a different thing entirely: it is the current *instance*. `Self.someStaticMember` is the same as `type(of: self).someStaticMember`. A requirement that mentions `Self` is called a **Self requirement**. It ties the requirement to the conformer's own type instead of to the protocol in general. ## Self in requirements: results and parameters Take a protocol whose conformers can duplicate themselves: ```swift protocol Duplicable { func copy() -> Self } ``` The requirement does not say "return something `Duplicable`". It says "return a value of *your own* type". A `Draft` must return a `Draft`; an `Invoice` must return an `Invoice`. The standard library's best-known Self requirement is in `Equatable`. In Swift 6.4 its declaration reads `static func == (lhs: borrowing Self, rhs: borrowing Self) -> Bool` (the `borrowing` keywords let noncopyable types adopt it). Both operands have type `Self`, so `==` always compares two values of the **same** conforming type. Comparing an `Int` with a `String` through `Equatable` is impossible by construction. `Self` may also appear in static requirements. An enum case without associated values satisfies a requirement for a get-only `static var` of type `Self`, so `case standard` satisfies `static var standard: Self { get }`. ## Structs, enums and final classes For a value type or a `final` class, the conforming type has exactly one possible dynamic type, so the conformer can write its own name where the protocol wrote `Self`: | Conformer | How it satisfies `func copy() -> Self` | |---|---| | `struct Draft` | `func copy() -> Draft` | | `enum Theme` | `func copy() -> Theme` | | `final class Invoice` | `func copy() -> Invoice` | | non-final `class Document` | `func copy() -> Self` only | The first three may also declare `-> Self`, but then the body must return `self` or build the value with `Self(...)`: in a `final class`, returning a fresh `Invoice()` from a `-> Self` method is rejected with "cannot convert return expression of type 'Invoice' to return type 'Self'". Writing the concrete name is the simpler spelling. ## Non-final classes: why `-> Self` is required A non-final class is different because a subclass inherits the conformance. If `Document` returned `Document`, then a `Report: Document` would claim to be `Duplicable` while its `copy()` returned a plain `Document`, breaking the promise. The compiler rejects that version with: ```plaintext error: method 'copy()' in non-final class 'Document' must return 'Self' to conform to protocol 'Duplicable' ``` Declaring `-> Self` creates a second obligation. To build a *new* instance of the dynamic type, the method writes `Self(title: title)`, which constructs through a metatype. Only a `required` initializer guarantees every subclass has that initializer, so without one the compiler reports "constructing an object of class type 'Self' with a metatype value must use a 'required' initializer". With both pieces in place, calling `copy()` on a `Document` variable that holds an `Invoice` returns an `Invoice`. The rule covers *results*. A parameter typed `Self` in a protocol, such as `Equatable`'s operands, is satisfied in a class by the class name: `static func == (lhs: Account, rhs: Account) -> Bool` compiles in a non-final class, because a subclass instance can always be passed where the base class is expected. ## Common mistakes 1. Reading `Self` as "the protocol type". It is the conformer's type; the protocol as a type is written `any Duplicable`, which is a different thing. 2. Treating `Self` and `self` as two spellings of one thing. One is a type, the other an instance. 3. Returning the class name from a non-final class and being surprised by the conformance error. 4. Forgetting `required` on the initializer that `Self(...)` calls. 5. Assuming `==` can compare values of different `Equatable` types. A Self requirement also has a cost at the use site: because the protocol now talks about "your own type", a value whose concrete type is hidden cannot always use it. That restriction belongs to the question of why such protocols could only be generic constraints before Swift 5.7.

  • Why does a non-final class need a `required` initializer to build a new instance inside `func copy() -> Self`?
    `Self` is the dynamic type, so a subclass calling the inherited `copy()` must get a subclass instance back. `Self(title: title)` constructs through the metatype, and only a `required` initializer is guaranteed to exist on every subclass. Without it the compiler reports "constructing an object of class type 'Self' with a metatype value must use a 'required' initializer".
  • Can an enum case satisfy a Swift protocol requirement that mentions `Self`?
    Yes. A case without associated values satisfies a get-only `static var` of type `Self`, and a case with associated values satisfies a `static func` returning `Self` whose parameter labels match. So `case standard` satisfies `static var standard: Self { get }` with no extra code.
  • How does a non-final class satisfy `Equatable`'s `==`, whose operands are typed `Self`?
    It writes the operator with its own class name, `static func == (lhs: Account, rhs: Account) -> Bool`, and that compiles. The must-return-Self rule is about results; a parameter typed with the base class already accepts every subclass instance.

  • Self in a protocol means the protocol type itself, as if you wrote its name.
  • Self and self are interchangeable spellings of the current instance.
  • A non-final class can satisfy func copy() -> Self by returning its own class name.
  • Equatable's == can compare any two Equatable values, even of different types.
  • A struct must spell the return type as Self, never its own name, to conform.