0

When I try to call super.init() before self.name or self.rating, Xcode shows an error.

Is it the rule that Class' properties need to init before calling super.init() if they are not optional? Or is there another reason for compiling?

Document says

Safety check 1 A designated initializer must ensure that all of the properties introduced by its class are initialized before it delegates up to a superclass initializer.

Whereas I think it could not apply for optional properties.


var name: String
var photo: UIImage?
var rating: Int

init?(name: String, photo: UIImage?, rating: Int) {
    self.name = name
    self.rating = rating

    super.init()

    // If self.name is declared in here, it will makes error. 
    //self.name = name 

    self.photo = photo // Optional values are exceptional. 

    if name.isEmpty || rating < 0 {
        return nil
    }
}

* Added *

I know this is the rule. but other answers did not explain clearly why Swift applied this rule.

Jeff Gu Kang
  • 4,749
  • 2
  • 36
  • 44
  • `name` and `rating` properties are not optional so they must exist before `super.init()` is called. – Ozgur Vatansever May 23 '16 at 05:14
  • "Is it the rule that Class' properties need to `init` before calling `super.init()` if they are not optional?" - Yes. – Rob May 23 '16 at 05:16
  • @Rob Thank you. Then, Is this rule existed for only safety issue that people forget init non-optional properties in `init()`? I did not understand clearly why we only declare properties init before calling `super.init()`. – Jeff Gu Kang May 23 '16 at 05:22
  • 1
    See WWDC 2014 [Intermediate Swift](https://developer.apple.com/videos/play/wwdc2014/403/), about 30 minutes into the video. They show example of what can go wrong if you don't follow this rule. Bottom line, (a) to maximize safety, we don't want to call any `self` methods until the object is fully initialized; and (b) you don't know what else other initializers higher in the object hierarchy might be doing, so out of an abundance of caution, the compiler is just making sure that all properties are initialized before your class (or any superclass) might start trying to use `self`. – Rob May 23 '16 at 05:50
  • @Rob Thank you for reply. I should check the video. – Jeff Gu Kang May 23 '16 at 05:51

0 Answers0