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.