A Swift subclass initializer calls a method and sets an inherited property before super.init, and the compiler rejects it; what does two-phase initialization require, and how do you fix it?
answer
- own properties first, then hand off
- no self until phase one ends
- inherited properties after super.init
- definite initialization diagnostics
- static helpers before super.init
basics
~20 sPhase one must give every stored property in the hierarchy a value, each class setting its own before calling super.init; only then may code use self. Fix it by setting the subclass's properties, calling super.init, then calling methods and assigning inherited properties.
solid answer
~40 sSwift initializes a class in two phases. In **phase 1** each designated initializer assigns the stored properties its own class introduces, then delegates up with `super.init`; when the root class finishes, the instance is fully initialized. In **phase 2**, back down the chain, initializers may use `self`: call methods, read properties, assign inherited ones. The compiler's definite-initialization pass enforces it: calling `describe()` early gives `'self' used in method call 'describe' before 'super.init' call`, assigning the inherited `name` early gives `'self' used in property access 'name' before 'super.init' call`, and leaving `radius` for later gives `property 'self.radius' not initialized at super.init call`. The fix is to reorder: own properties, then `super.init`, then the customisation. A value needed before `super.init` comes from the parameters, a local, or a `static` helper, which needs no instance.
code
swift · 17 linesclass Shape {
var name: String
init(name: String) { self.name = name }
func describe() -> String { "shape \(name)" }
}
class Circle: Shape {
var radius: Double
var label: String
init(radius: Double) {
label = describe()
name = "circle r=\(radius)"
super.init(name: "circle")
self.radius = radius
}
}go deeper
Remember the order in a subclass designated initializer: set your own stored properties, call super.init, then use self.
Explain the two phases and which of the four safety checks each piece of code would break.
Read a definite-initialization error, name the safety check behind it, and restructure the initializer with static helpers or phase-2 assignments instead of weakening property types.
Use the rules to keep class initializers small and predictable, and push heavy setup out of initializers where an overridable call could run during super.init.
## The two phases **Two-phase initialization** is how Swift guarantees that no code ever sees a class instance with an uninitialized stored property. 1. **Phase 1, going up.** The initializer that was called runs a designated initializer of the class. That initializer gives a value to every stored property **its own class introduces**, then hands off to a designated initializer of the superclass with `super.init`. Each class does the same until the root class has set its properties. At that moment the instance's memory is **fully initialized**. 2. **Phase 2, coming back down.** Control returns through each designated initializer, then any convenience initializer. Now each one may **customize** the instance: read and write any property, including inherited ones, call instance methods, and pass `self` elsewhere. The point is that in phase 1 `self` is incomplete, so nothing may observe it. ## The four safety checks The Swift book lists four checks the compiler performs: - **Check 1**: a designated initializer must initialize all properties **introduced by its class** before delegating up. - **Check 2**: a designated initializer must delegate up **before** assigning a value to an **inherited** property; otherwise the superclass initializer would overwrite it. - **Check 3**: a convenience initializer must delegate (`self.init`) before assigning **any** property. - **Check 4**: no initializer may call an instance method, read an instance property, or use `self` as a value until phase 1 is complete. ## Mapping the errors to the checks These errors come from the **definite-initialization** pass, which runs on SIL after type checking; their texts are in the compiler's `DiagnosticsSIL.def`. | Code in `Circle.init(radius:)` | Check | Swift 6.4 error | |---|---|---| | `label = describe()` before `super.init` | 4 | `'self' used in method call 'describe' before 'super.init' call` | | `name = "..."` (inherited) before `super.init` | 2 | `'self' used in property access 'name' before 'super.init' call` | | `self.radius = radius` after `super.init` | 1 | `property 'self.radius' not initialized at super.init call` | | reading `super.name` before `super.init` | 4 | `'self' used in property access 'name' before 'super.init' call` | The same discipline applies to a root class or a struct: calling a method before every stored property is set gives `'self' used before all stored properties are initialized` in a struct, and `'self' used in method call 'register' before all stored properties are initialized` in a root class. ## How to fix the broken initializer Reorder the body around the `super.init` call: - **Before `super.init`**: assign each property `Circle` introduces (`radius`, `label`). Use only parameters, local constants, and **`static`** functions, which need no instance (`label = Circle.makeLabel(radius)` compiles). - **The call**: `super.init(name:)`. - **After `super.init`**: assign inherited properties (`name`), call instance methods (`describe()`), and overwrite any placeholder you set in phase 1. If a stored property really can only be computed from a fully initialized `self`, the options are to give it a placeholder value and replace it in phase 2, or to compute it on demand instead of storing it; making it an implicitly unwrapped Optional just to satisfy the checker trades a compile error for a possible run-time trap. ## Why Swift insists The order pays off when a superclass initializer calls an overridable method. If `Shape.init` calls `describe()` and `Circle` overrides it to read `radius`, the override runs during `super.init`, and because check 1 forced `radius` to be set first, it sees the real value: on Swift 6.4, `Circle(radius: 3)` built this way prints `circle r=3.0` from inside `Shape.init`. Languages that let a subclass field stay at a zero value at that point turn this into a classic bug; Swift rules it out at compile time. ## Convenience initializers and structs The same idea applies outside designated class initializers, with a different boundary: - A **convenience initializer** has no phase-1 work of its own: until `self.init(...)` returns it may not read or write any property, and the error then names `self.init` instead of `super.init`. - A **struct** initializer that delegates with `self.init(...)` follows the same rule as a convenience initializer. - A struct initializer that assigns properties itself may call methods only after **every** stored property has a value. In all three cases the instance is unusable until its storage is complete; only the call that completes it differs. ## Reading the diagnostics in a review - An error naming **`super.init`** means phase 1 is not finished where `self` was used. - An error naming a **property at `super.init`** means the subclass handed off too early. - An error mentioning **`self.init`** is about a convenience initializer, not a designated one.
- Why does Swift make you set subclass properties before super.init when many languages do the opposite?Because a superclass initializer may call a method the subclass overrides. With every subclass property already set, that override reads real values. Swift proves this at compile time instead of leaving subclass fields at a zero value during the superclass initializer.
- How do you compute a stored property from other inputs before super.init without touching self?Use the initializer's parameters, local constants, or a `static` function such as `Circle.makeLabel(radius)`; none of them needs an instance. An instance method, even a `private` or `final` one, still uses `self` and is rejected before phase 1 ends.
- Call super.init first in a Swift subclass initializer, then set the subclass's own properties.
- Marking the helper method final makes it safe to call before super.init.
- Reading super.name before super.init is fine because the property belongs to the superclass.
- An implicitly unwrapped optional property is always the right fix for a two-phase error.
- These errors only appear at run time when the object is first created.