skip to content

In Swift classes, how do designated and convenience initializers differ, and which delegation rules does the compiler enforce between them?

level: middleimportance: must knowfreq 55%

answer

  1. primary versus secondary initializers
  2. the convenience keyword
  3. delegate up, delegate across
  4. self.init versus super.init

basics

~20 s

A designated initializer fully initializes the properties its class introduces and, in a subclass, calls a designated initializer of the immediate superclass. A convenience initializer, marked convenience, must call another initializer of the same class with self.init, ultimately reaching a designated one.

solid answer

~50 s

A **designated** initializer is a class's primary initializer: it gives every stored property the class introduces a value, then chains to a designated initializer of the immediate superclass with `super.init`. A **convenience** initializer is marked `convenience` and must delegate with `self.init` to another initializer of the same class, so every path ends in a designated one. The short form is "designated delegates up, convenience delegates across". The compiler enforces it: a convenience init calling `super.init` is rejected with "must delegate (with 'self.init') rather than chaining to a superclass initializer", and a designated init calling `self.init` is told it "cannot delegate" and asked whether it meant to be a convenience initializer. The rules only govern how initializers are implemented; callers can use any of them. Structs have no `convenience` keyword: any struct initializer may call `self.init`.

code

swift · 23 lines
swift
class Shape {
    var name: String
    var strokeWidth: Double
    init(name: String, strokeWidth: Double) {
        self.name = name
        self.strokeWidth = strokeWidth
    }
    convenience init(name: String) {
        self.init(name: name, strokeWidth: 1.0)
    }
}
class Circle: Shape {
    var radius: Double
    init(radius: Double) {
        self.radius = radius
        super.init(name: "circle", strokeWidth: 1.0)
    }
    convenience init(diameter: Double) {
        self.init(radius: diameter / 2)
    }
}
let c = Circle(diameter: 10)
print(c.radius, c.name)

go deeper

for a junior

Recall the two kinds: designated initializers set the class's own properties and, in a subclass, call super.init; convenience initializers are marked convenience and call self.init.

for a middle

Explain delegate up versus delegate across, why the chain must end in a designated initializer, and quote what the compiler says when a convenience init calls super.init.

for a senior

Diagnose a hierarchy that does not compile: a convenience init touching self early, a designated init calling a superclass convenience init, or a missing super.init with no zero-argument init.

for a principal

Treat designated initializers as the funnel of a class's API: keep them few and complete, and add convenience initializers for alternate inputs rather than more designated ones.

## Two kinds of class initializer Swift classes can inherit stored properties, so the compiler needs a guarantee that **every** stored property in the hierarchy gets a value exactly once. It gets that guarantee by splitting class initializers into two kinds: - A **designated initializer** is the primary one. It must give a value to every stored property **introduced by its own class**, then call a **designated** initializer of the **immediate superclass** (unless the class has no superclass). Every class has at least one, written or inherited. - A **convenience initializer** is a secondary one, written with the `convenience` modifier. It must call **another initializer of the same class** with `self.init(...)`, and the chain must end at a designated initializer. It typically supplies default arguments or converts a different input, such as a diameter instead of a radius. The book calls designated initializers the "funnel" points: however many convenience initializers a class offers, construction always passes through a designated one, and from there up the hierarchy. ## The three delegation rules The Swift book states them as: 1. A designated initializer must call a designated initializer from its **immediate superclass**. 2. A convenience initializer must call **another initializer from the same class**. 3. A convenience initializer must **ultimately** call a designated initializer. The short form is **designated initializers delegate up; convenience initializers delegate across**. A convenience initializer may call another convenience initializer, as long as the chain ends in a designated one. ## What the compiler says when you break them | Mistake | Swift 6.4 diagnostic | |---|---| | convenience init calls `super.init` | `convenience initializer for 'Circle' must delegate (with 'self.init') rather than chaining to a superclass initializer (with 'super.init')` | | designated init calls `self.init` | `designated initializer for 'Shape' cannot delegate (with 'self.init'); did you mean this to be a convenience initializer?` | | designated init calls a superclass **convenience** init | `must call a designated initializer of the superclass 'Shape'` | | convenience init touches `self` before `self.init` | `'self' used before 'self.init' call or assignment to 'self'` | The last row matters in practice: a convenience initializer may compute values into **local constants** first, but it cannot read or assign any property, including the class's own, until `self.init` has returned. Anything it assigned earlier would be overwritten by the designated initializer anyway. ## The Shape and Circle example In the example below, `Shape` has one designated initializer and one convenience initializer that fills in a default stroke width. `Circle` adds `radius`, has its own designated `init(radius:)`, which sets `radius` and then calls `super.init(name:strokeWidth:)`, and offers `convenience init(diameter:)`, which converts its input and delegates across to `init(radius:)`. A few details that interviewers like to probe: - When the superclass has a zero-argument designated `init()`, the compiler inserts the `super.init()` call at the end of a subclass designated initializer for you; with no such initializer, omitting the call is an error (`'super.init' isn't called on all paths before returning from initializer`). - The rules affect only the **implementation**. A caller can create a `Circle` through any initializer it can see; nothing marks convenience initializers as second class at the call site. - `override` is written when a subclass initializer matches a superclass **designated** initializer, even if the subclass implements it as a convenience initializer. ## Tracing one call Following `Circle(diameter: 10)` through the example shows both rules at work: 1. `convenience init(diameter:)` computes `diameter / 2` and delegates **across** with `self.init(radius: 5)`. 2. The designated `init(radius:)` assigns `radius`, the only property `Circle` introduces, and delegates **up** with `super.init(name: "circle", strokeWidth: 1.0)`. 3. `Shape`'s designated initializer assigns `name` and `strokeWidth`. `Shape` has no superclass, so every stored property now has a value. 4. Control returns down the chain: first `Shape`'s initializer, then `Circle.init(radius:)`, then the convenience initializer, each of which may now use `self` to customise the instance. Every path through any initializer of `Circle` passes through step 2, which is what the funnel image means. ## Structs are simpler Value types have no inheritance, so there is nothing to delegate up to. A struct initializer simply calls `self.init(...)` to reuse another initializer, and the `convenience` keyword is not allowed there: the compiler reports `initializers in structs are not marked with 'convenience'`. The designated/convenience vocabulary, and the up/across rules, are a class feature. ## Why the rules exist The split exists so that two-phase initialization can be checked statically: the designated chain is the path along which each class sets its own stored properties before handing off upward. Convenience initializers stay on the outside of that path, which is why they can only go across, and why they can only use `self` after the designated initializer has finished.

  • Can a convenience initializer set a property before calling self.init?
    No. Until `self.init` returns, a convenience initializer cannot read or write any property, including its own class's; the compiler reports `'self' used before 'self.init' call or assignment to 'self'`. It can compute values into local constants first and pass them to `self.init`, then adjust properties afterwards.
  • When does a subclass designated initializer not need an explicit super.init call?
    When the superclass has a zero-argument designated `init()`, the compiler inserts `super.init()` at the end of the subclass initializer. If the superclass has no such initializer, the call is required, and leaving it out is an error: `'super.init' isn't called on all paths before returning from initializer`.

  • A convenience initializer can call super.init directly to skip a step.
  • A designated initializer may hand off to another designated initializer of the same class with self.init.
  • Struct initializers that call self.init must be marked convenience.
  • Callers cannot create an instance through a convenience initializer of a subclass.
  • Convenience initializers may assign the class's own properties before self.init.