Swift UIViewController Custom init() - Error cannot assign to self

640 Views Asked by At

In Objective-C I used to override the init method of my UIViewController. I cannot achieve the same in Swift :

Objective-C code :

- (instancetype)init
{
    self = [super init];
    if (self) {
        self = [[UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"ViewController"];
    }
    return self;
}

If I try to do so in Swift I get errors for "Cannot assign to self". I have already implemented the initWithCoder: method just to get through a few more errors.

Can someone please tell me how can I port the above Objective-C code to Swift to get the desired behavior.

I want to init the ViewController from storyboard.

3

There are 3 best solutions below

0
On

You cannot assign self in init. You should use class method or public function instead.

class func viewControllerFromStoryboard() -> ViewController? {
    let storyboard = UIStoryboard(name: "Main", bundle: NSBundle(forClass: ViewController.self))
    if let controller = storyboard.instantiateViewControllerWithIdentifier("ViewController") as? ViewController
    {
        return controller
    }
    return nil
}

After you can call

let controller = ViewController.viewControllerFromStoryboard()
0
On

Init method in swift is different from the ones in objc.

In objc the only requirement for init method is that the initializing method begins with the letters “init”. You create a instance in this method and assign to pointer self

whereas in swift Initializing is the process of preparing an instance of a class, structure, or enumeration for use. It's kind of like you already has a self point to an instance. What you do in init method is set up self's properties and other

That's why you cannot assign to self in swift for class

but you can assign to self in a mutating method of struct

0
On

I suggest you write like this

class func customInit -> XXXController {
    var vc: XXXController = XXXController()
    //  write something that you want to initialize 
    return vc 
}

just like you write objc

- (instancetype)initCustom {
    self = [super init];
    if (self) {
       //  write something that you want to initialize 
    }
    return self; 
}

and you can cell

var customVc: XXXController = XXXController.customInit()

just like

XXXController *vc = [[XXXController alloc] initCustom]