0

Safety Check #4

An initializer cannot call any instance methods, read the values of any instance properties, or refer to self as a value until after the first phase of initialization is complete.

class Fruit {
  var name: String
  init(fruitName: String) {
    // in phase one
    self.name = fruitName; // using self during the property assignment
    // phase one is complete
  }
}

let orange = Fruit(fruitName: "Orange");

So, how does this get special dispensation to use self, and to know what self refers to?

  • Either I misinterpret your question, or you misinterpreted that quote. Does that code work? Also, maybe [this related question](http://stackoverflow.com/questions/28431011/swift-why-i-cant-call-method-from-override-init) is useful to you. – GolezTrol Jun 23 '15 at 18:17
  • @GolezTrol Yes that code works in Playground. I understand the quote to mean that when `self.name = fruitName` is evaluated, `self` shouldn't exist until `name` has been assigned, therefore it would fail. –  Jun 23 '15 at 18:48
  • 1
    You are simply setting an initial value for a stored property. That does not count as "refer to self as a value". – Martin R Jun 23 '15 at 18:50

2 Answers2

0

or refer to self as a value until after the first phase of initialization is complete.

This is a case here the first phase is ready, how you want assign properties of your instance without self ? A more useful example is when you override init method.

You can't use self before super.init()

Lory Huz
  • 1,557
  • 2
  • 15
  • 23
  • How is the first phase ready, the point at which I assign `self.name = fruitName`, the property has not been assigned, therefore Phase 1 hasn't finished. –  Jun 23 '15 at 18:49
  • It's not what they mean with first phase of initialization, like I said with my example – Lory Huz Jun 23 '15 at 18:58
0

In two-phase initialization, phase 1 ends when top of the chain is reached, and the final class in the chain has ensured that all of its stored properties have a value.

This means:

class Fruit { var name: String init(fruitName: String) { self.someFunction() // compilation error, since not all stored properties have value yet, self is not allowed to refer as a value self.name = fruitName; // self is refer here only for initializing property // phase one completed self.someFunction() // no problem here } func someFunction() { print("phase one completed") } }

David Liu
  • 16,374
  • 12
  • 37
  • 38
  • This is not correct. Try `let otherFruit = self` *before* assigning an initial value to `self.name`, it will give a compiler error because phase 1 is not yet completed. – Martin R Jun 23 '15 at 19:45