Marcus Leon
Marcus Leon

Reputation: 56669

Swift: Convenience initializers - Self used before self.init call

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

Answers (1)

Smnd
Smnd

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

Related Questions