Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create convenience Initializer on subclass that calls failable Initializer

Tags:

ios

swift

Tried many variations of the derivation below but none work.

import Foundation
import SceneKit


class test:SCNScene{
    override init(){
        super.init()
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }


    convenience init? (i:UIViewController){
        self.init(named:"") //Compile Error:use of self delegating initializer before self.init is called
    }

}

According to Swift documentation, rule 2 of initialization, shouldn't init?(named:String) convenience failable Initializer be available after implement the 2 designated Initializer? What am i getting wrong?

like image 517
MiguelSlv Avatar asked Feb 12 '23 14:02

MiguelSlv


1 Answers

The initialiser delegation rule #2 states

A convenience initializer must call another initializer from the same class.

Your class doesn't define init?(named:String), so it will call superclass initialiser (which you do have access to under the other rule #2 you were referring to), but this won't satisfy the requirement to call a non-convenience initialiser from your class.

You can simply call self.init before calling the superclass initialiser.

convenience init? (i:UIViewController){
        self.init()
        self.init(named:"") 
}
like image 92
Paulw11 Avatar answered Feb 14 '23 09:02

Paulw11