The problem is that each property declared with let
in a class
must be populated before the init
does return.
In your case the init
is not populating the 2 constant properties.
In Swift 2.1 each constant property of a class
must be populated even when a failable initializer does fail.
class Foo {
let a: Int?
let b: Int?
init?() {
return nil // compile error
}
}
More details here.
Struct
On the other hand you can use a struct
where a failable initializer
can return nil
without populating all the let
properties.
struct Person {
let name: String
init?(name:String?) {
guard let name = name else { return nil }
self.name = name
}
}