Ali
Ali

Reputation: 515

Where is initialization taking place, in the init method or in the instance declaration?

Please don't ask me to go read a link on the apple website, because I've read all of it!

Im confused on where the actual initialization of the property 'text' is taking place? Is it in the init method or is it happening in the instance declaration?

Because it seems to me that the initialization of the text property is happening in the instance declaration where it's being given the value "How about beets?"

And if so, then why does the apple book state that all properties must be initialized before an instance is created; within the class definition (correct me if I'm wrong)

Lastly if 'text' is actually being initialized in the class definition....where is the initialization??

class SurveyQuestion {

let text: String
var response: String?
init(text: String) {
    self.text = text
  }
func ask() {
    print(text)
   }
}
  let beetsQuestion = SurveyQuestion(text: "How about beets?")

Upvotes: 0

Views: 41

Answers (2)

Marc
Marc

Reputation: 521

I believe the process followed in you code is:

  1. You call SurveyQuestion(text: "How about beets?") to get an instance of the SurveyQuestion class.
  2. When the class is running it's initialization method init(text: String) it initializes all the properties. That means you're initializing the text property, giving it a value.
  3. Finally the class finishes initialization and you get an instance of that class.

That corresponds to Apple's documentation as when you initialize the class the properties are initialized but you don't get the class instance until the init method has finished, and that means until all properties are initialized.

Sorry for the initialization redundance, I didn't find another way to explain it. I hope that solves your doubts.

Upvotes: 0

mipadi
mipadi

Reputation: 411252

The initialization takes place in the init method. Note that init takes one parameter, text, and assigns that parameter to self.text.

Upvotes: 2

Related Questions