The key to your confusion is what it means for a subclass to initialize a constant property. This means that a subclass cannot introduce an initializer that assigns the value. Let's consider a simple case:
class Person {
let name: String
init() {
name = "Alice"
}
}
This could be more simply written by assigning name
in its declaration, but I'm hoping this is clearer. Now we want to create a subclass that assigns name
to something else. The obvious way to do this (and how you'd do it in languages that don't have constant properties) would be to assign it after calling super.init()
:
class Employee: Person {
override init() {
super.init()
name = "Bob" // error: cannot assign to property: 'name' is a 'let' constant
}
}
Nope. We run into exactly the case described in your excerpt. Well, maybe we should assign it first?
class Employee: Person {
override init() {
name = "Bob" // error: cannot assign to property: 'name' is a 'let' constant
super.init()
}
}
Nope. No better.
Ah! It's because we call super.init()
. Let's just not call it.
class Employee: Person {
override init() {
name = "Bob" // error: cannot assign to property: 'name' is a 'let' constant
}
}
No... When they say you can't do this, they mean you can't do this. You can explore more, for instance changing the class to:
class Person {
let name = "Alice"
}
And you'll find you have all the same problems. You cannot assign to a let
constant in a superclass from a method introduced in a subclass.