Swift UIViewController Custom init () - Error cannot be assigned to itself

In Objective-C, I used a method override of init

mine 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 this in Swift, I get errors for "Can't assign myself". I've already implemented a method initWithCoder:

to get some more errors.

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

I want to launch ViewController from storyboard.

+3


source to share


3 answers


You cannot assign self

to init

. You should use a method class

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 calling

let controller = ViewController.viewControllerFromStoryboard()

      

+2


source


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

Objc the only requirement for init method is that the initializing method begins with the letters "init"

. You instantiate in this method and assign to the pointerself

whereas in swift Initializing is the process of preparing an instance of a class, structure, or enumeration for use

. It looks like you are already pointing self

to an instance. What you are doing in the init method is setting properties and other



This is why you cannot assign yourself to the fastest class

but you can assign yourself to the mutating struct method

0


source


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 use cell

var customVc: XXXController = XXXController.customInit()

as

XXXController *vc = [[XXXController alloc] initCustom]

0


source







All Articles