Question regarding initializer, self, and implicitly unwrapped optional

I’m reading Apple’s Swift tutorial on ARC and there’s something that I don’t understand (link: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html#//apple_ref/doc/uid/TP40014097-CH20-ID48)

 

 

class Country {

  let name: String

  var capitalCity: City!

  init(name: String, capitalName: String) {

      self.name = name

      self.capitalCity = City(name: capitalName, country: self)

  }

}

class City {

  let name: String

  unowned let country: Country

  init(name: String, country: Country) {

      self.name = name

      self.country = country

  }

}

 

Apple says: “The initializer for City is called from within the initializer for Country. However, the initializer for Country cannot pass self to the City initializer until a new Country instance is fully initialized,”

 

What does it mean to pass self to the City initializer? and why can’t Country’s initializer pass self to CIty’s initializer until a new Country instance is fully initialized?

 

Apple also says: “To cope with this requirement, you declare the capitalCity property of Country as an implicitly unwrapped optional property,”

 

What requirement? The requirement that a new Country instance has to be fully initialized? How does declaring the capitalCity property as implicitly unwrapped optional fulfill this requirement?

Powered by WPeMatico

About

You may also like...

Comments are closed.