In a class that has a failable initializer, all the variables must be set before returning nil.
This is a near copy from the Swift Programming Language Guide:
class Product {
let name: String // The guide has this as String! so it can compile
init?(name: String) {
if name.isEmpty { return nil }
self.name = name
}
}
The guide tells us that name
needs to be String!
, and true enough the above does not compile.
We're told "For classes, however, a failable initializer can trigger an initialization failure only after all stored properties introduced by that class have been set to an initial value and any initializer delegation has taken place." But the guide doesn't explain the reason value types are allowed to skip setting all the variables, while reference types must do so.
My question is why are classes required to initialize all the variables?