Daily iOS
Swift

Initialization rules

Why doesn't this code compile? Can you explain it using the two-phase initialization rules?

class Base { let id: Int; init(id: Int) { self.id = id } }
class Child: Base {
    let name: String
    init(name: String) {
        super.init(id: name.count)
        self.name = name
    }
}
How would an interviewer hear this answer? You'll see whether they'd move on, dig in, or say no, and which sentences would trip you up. Your score doesn't change.
See the short answer

A subclass's stored properties must all be initialized before calling super.init; that's phase 1 of two-phase initialization. Write self.name = name first, then call super.init.

Share a question