Detect if a init? returned nil in another initializer

I have a class with two initializers, the first one is something like

init?(){
    if ..... { return nil }
    // attributes initialization
}

and the second one is a convenience initializer that calls the first one, however I would like to detect if the first initializer has returned nil, otherwise I wouldn't continue with my code. I tried with something like the code below but it didn't work for me.

convenience init?(value: Int) {
    if let myObject = self.init() {
         return nil
    }
    self.value = value
}

I also tried to assign it directly to a variable but it looks that the compiler doesn't like that. Is there a way to detect it without adding a boolean as attribute?

Upvotes: 3

Views: 494

Answers (1)

rintaro
rintaro

Reputation: 51911

You cannot detect failure if you delegated to another initializer. From the document: Propagation of Initialization Failure

In either case, if you delegate to another initializer that causes initialization to fail, the entire initialization process fails immediately, and no further initialization code is executed.

If you just want to return nil if failed, just leave it.

class Foo {
    var name:String
    var x = 1

    init?(name:String) {
        self.name = name
        if name == "" {
            return nil
        }
    }

    convenience init?(name:String, x:Int) {
        self.init(name:name)

        // Not executed if self.init(name:) failed.
        self.x = x
    }
}

Foo(name: "", x:12) // -> nil
Foo(name: "foo", x:42) // -> {name:"foo" x:42}

Upvotes: 6

Related Questions