skip to content

Why does a Swift subclass that adds its own designated initializer stop inheriting its superclass's initializers, and how does required change that?

level: seniorimportance: should knowfreq 35%

answer

  1. not inherited by default
  2. rule 1: no designated initializers
  3. rule 2: all designated ones covered
  4. required forces every subclass
  5. metatype construction

basics

~20 s

Swift subclasses inherit superclass initializers only when it is safe: all designated ones when the subclass defines none and gives new properties defaults, convenience ones once it covers every designated one. Marking an initializer required forces every subclass to provide it.

solid answer

~40 s

Swift subclasses do not inherit superclass initializers by default, so an inherited `init(name:)` can't build a `Circle` with no `radius`. Two rules apply when every new stored property has a default value. **Rule 1**: a subclass that defines no designated initializer inherits all of its superclass's designated initializers. **Rule 2**: a subclass that implements every superclass designated initializer, by inheriting or overriding it, also inherits all the convenience ones. So once `Circle` adds `init(radius:)`, `Circle(name:)` and `Circle()` stop compiling; writing `override convenience init(name:)` brings both back. A **`required`** initializer goes further: every subclass must provide it, by rule 1 or by writing `required init(...)` (`override` is implied), or it fails with "'required' initializer 'init(name:)' must be provided by subclass". It is what makes `type.init(name:)` on a metatype legal.

code

swift · 28 lines
swift
class Shape {
    var name: String
    init(name: String) { self.name = name }
    convenience init() { self.init(name: "shape") }
}

// No designated init, every new property has a default: inherits both.
class Square: Shape {
    var side = 1.0
}

// Its own designated init: inherits neither until it overrides init(name:).
class Circle: Shape {
    var radius: Double
    init(radius: Double) {
        self.radius = radius
        super.init(name: "circle")
    }
    override convenience init(name: String) {
        self.init(radius: 1)
        self.name = name
    }
}

let s = Square()               // inherited convenience init()
let c1 = Circle(name: "ring")  // the override
let c2 = Circle()              // inherited again by rule 2
print(s.name, c1.name, c2.name, c2.radius)

go deeper

for a junior

Recall that a Swift subclass does not inherit initializers automatically, and that required means every subclass must have that initializer.

for a middle

State the two inheritance rules and walk through which initializers a subclass with and without its own designated initializer can offer.

for a senior

Diagnose a subclass that lost an initializer, fix it by overriding every designated initializer, and explain when required is needed, including metatype construction.

for a principal

Decide which initializers form the contract for subclasses of a base class, mark them required deliberately, and prefer final where subclassing is not part of the design.

## The default: no inheritance In Swift, a subclass **does not inherit** its superclass's initializers by default. The reason is safety: if `Circle` adds `var radius: Double` with no default, an inherited `Shape.init(name:)` would create a `Circle` whose `radius` was never set. Swift refuses to allow that, so inheritance happens only when the compiler can prove it is safe. In the Shape example, `Shape` has a designated `init(name:)` and a convenience `init()`. A subclass `Circle` with a designated `init(radius:)` therefore offers **only** `init(radius:)`: `Circle(name: "ring")` fails with `incorrect argument label in call (have 'name:', expected 'radius:')`. ## Automatic initializer inheritance Assuming every stored property the subclass adds has a **default value**, two rules apply: 1. **Rule 1**: if the subclass defines **no designated initializers**, it inherits **all** of its superclass's designated initializers. 2. **Rule 2**: if the subclass provides an implementation of **all** of its superclass's designated initializers, by inheriting them under rule 1 or by overriding them, it also inherits **all** of the superclass's **convenience** initializers. The rules hold even if the subclass adds convenience initializers of its own, and a superclass designated initializer may be implemented as a subclass **convenience** initializer to satisfy rule 2. In the example: - `Square` adds `var side = 1.0` and no initializers, so rule 1 gives it `init(name:)` and rule 2 gives it `init()`. - `Circle` adds `init(radius:)`, which switches rule 1 off. By writing `override convenience init(name:)` that delegates to `init(radius:)`, it implements every `Shape` designated initializer, so rule 2 gives `init()` back. A subtle consequence: the inherited `init()` calls `self.init(name: "shape")`, which dispatches to **Circle's** override, so `Circle()` builds a circle with the default radius. ## Required initializers Writing `required` before a class initializer means **every subclass must provide it**. - A subclass that inherits it under rule 1 already provides it; `Square` needs no code. - A subclass that defines its own designated initializers must write it out, again marked `required` (the `override` modifier is implied, and writing it draws a warning: `'override' is implied when overriding a required initializer`). - Forgetting it is an error at the class declaration: `'required' initializer 'init(name:)' must be provided by subclass of 'Shape'`. | Situation | Inherits `init(name:)`? | Inherits `init()`? | |---|---|---| | Subclass adds defaulted properties, no initializers | Yes (rule 1) | Yes (rule 2) | | Subclass adds `init(radius:)` only | No | No | | …plus `override convenience init(name:)` | Its own override | Yes (rule 2) | | Property without a default and no initializer | Error: `class 'Sq' has no initializers` | — | ## Why required exists `required` is how a class promises that **every subclass can be built the same way**, which matters whenever code constructs an instance from a **type value** it does not know statically. Calling `t.init(name: "x")` on a `Shape.Type` compiles only if that initializer is `required`; otherwise the compiler says `constructing an object of class type 'Shape' with a metatype value must use a 'required' initializer`. Protocol initializer requirements lead to the same keyword on non-final classes, which is the material on protocol requirements; the familiar case on Apple platforms is the decoding initializer `init?(coder:)` that a UIKit view subclass must also implement once it adds its own designated initializer. ## A checklist for a new subclass When a subclass does not offer the initializer you expected, walk the rules in order: 1. Does every stored property the subclass adds have a **default value**? If not, automatic inheritance is off, and a class with no initializer at all fails with `class ... has no initializers`. 2. Does the subclass declare **any designated initializer**? If so, rule 1 no longer applies and none of the superclass's designated initializers come along. 3. Does it implement **every** superclass designated initializer, as an override or an inherited one? Only then does rule 2 bring the convenience initializers. 4. Is any superclass initializer **`required`**? Then the subclass must end up with it, by inheriting or by writing `required init(...)`. ## What to look for in a review - A subclass that suddenly lost `init(name:)` gained a designated initializer or a stored property without a default. - Overriding every superclass designated initializer restores the convenience initializers in one step. - A `final` class cannot have subclasses, so the inheritance question disappears; a class meant for subclassing should decide early which initializers are `required`.

  • Does a subclass have to write anything to satisfy a required initializer?
    Not always. If it defines no designated initializers and its new properties have defaults, it inherits the required initializer under rule 1. Once it declares its own designated initializer, it must write `required init(...)` itself, or the class declaration fails with `'required' initializer ... must be provided by subclass`.
  • Why does constructing an instance from a metatype need a required initializer?
    A `Shape.Type` value may hold any subclass. The compiler can only allow `t.init(name:)` if every subclass is guaranteed to have that initializer, which is exactly what `required` promises; otherwise it reports `constructing an object of class type 'Shape' with a metatype value must use a 'required' initializer`.

  • Swift subclasses inherit every superclass initializer, as long as they call super.init.
  • Adding a convenience initializer to a subclass switches off inherited designated initializers.
  • A required initializer must be re-declared in every subclass, even when it is inherited.
  • You write override required init in the subclass to satisfy a required initializer.
  • Overriding a designated initializer as a convenience initializer cannot satisfy rule 2.