Reputation: 56669
We are getting the following error on the convenience method below:
Self used before self.init call
class MyClass {
var id : Int
var desc : String
init?(id : Int, desc : String) {
self.id = id
self.desc = desc
}
convenience init?(id : Int?) {
guard let x = id else {
return
}
self.init(id : x, desc : "Blah")
}
}
How can we implement this type of behavior in Swift?
Upvotes: 27
Views: 19295
Reputation: 1579
As Leo already pointed out, the quickest way of appeasing the compiler is to return nil inside the guard statement.
convenience init?(id : Int?) {
guard let x = id else {
return nil
}
self.init(id: x, desc: "Blah")
}
Unless there is a specific reason to do so, you can also avoid using a failable initializer in the first place.init(id : Int, desc : String)
compiles just fine.
Upvotes: 39