SLN SLN - 9 months ago 23
Swift Question

Constant property can be modified during initialization? MODIFIED? What?

Quote from the Swift 3.0 office document of the Chapter: Initialization

For class instances, a constant property can be modified during initialization only by the class that introduces it. It cannot be modified by a subclass.

To my understanding the modified involves the action after the definition, aka the action after declaring and assigning value, aka re-assigning values, therefore I tried the following code.

class SurveryQuestion {
let text: String
var response: String?
init(text: String) {
self.text = "do you like music?"
self.text = text //Got an error here
func ask(){

And I got an error at line
self.text = text
. The compiler asked me to change the property
from constant to variable. Isn't it says that the constant property can be modified by the initializer of the class which originally introduced it?

Question: Am I understand the word modified wrongly? Is it means the action after the declaring rather than the definition which would lead to the modified is meant to by passing a value to the constant.


I think that the documentation is not clear enough. You can set a constant property only once during initializing. You also would not be able to set it during initialization if the property's value was defined inline. Here is example.

class SomeClass {

    let someProperty: String = "A"

    init() {

        self.someProperty = "" //ERROR: Immutable value "self.someProperty" may only be initialized once.

The compile time error //ERROR: Immutable value "self.someProperty" may only be initialized once. actually explains it well.