gexicide
gexicide

Reputation: 40068

Swift: Overriding a convenience with a designated initializer

The Swift documentation states the following:

If the initializer you are overriding is a convenience initializer, your override must call another designated initializer from its own subclass, as per the rules described above in Initializer Chaining.

This means, that when I define an initializer with the same signature as a convenience initializer from the base class, then it must also act as a convenience initializer. I cannot "override" a convenience initializer with a designated initializer.

This seems awkward to me: There might be various cases where a signature, e.g., (String) is only a convenience init for the base class but a designated init for a subclass. In contrast to methods, only because two initializer have the same signature, they do not have to perform a similar task. A signature of (String) could mean something completely different for a subclass.

  1. So, why did they add this restriction?
  2. How can I circumvent it? I.e., if I do need a non-convenience initializer with the same signature as a convenience initializer in the base class, what should I do? My only guess would be adding an unused dummy parameter only to distinguish between them. But this seems very hacky

Upvotes: 4

Views: 3403

Answers (1)

Roshan
Roshan

Reputation: 1937

What they mean is that if the initialiser that you have after overriding is a convenience initialiser, then you must follow Initialiser Chaining.

The following works fine meaning you can override a convenience initialiser with a designated initialiser :

class Base {
    var x = 0
    init() {}
    convenience init(_: Int) {
        self.init()
        self.x = 5
    }
}

class Derived : Base {
    init() {}
    init(_: Int) {
        super.init()
        self.x = 10
    }
}

var i = Derived(1)     // x = 10

Upvotes: 3

Related Questions