How to Fix “Class ViewController has no initializers” Error in IOS Xcode

While working in Swift, we usually see this error “Class ViewController has no initializers”. It’s not specifically for ViewController rather it can be related to any of our class. It’s a compile-time error we usually face in Xcode. In this article, we will discuss the reason for this error and then its solution.

Reason for “Class ViewController has no initializers” Error

Swift has very strict rules regarding initializations of the variables and class data members. So this happens when we don’t assign any default value to any data member of the class, as you can see in the following example.

class YourViewController: UIViewController {
    var name: String
}

If we write the above code we will see the following error in Xcode.

Class ViewController has no initializers

Solution to the “Class ViewController has no initializers” Error

1. Initialization of Class Data members at the time of declaration

The simplest solution to the problem is to assign some value to the data members of the class. That means, initialization of the class data members at the time of declaration. For example

class YourViewController: UIViewController {
    var name: String = "Asad"
}

2. Declaring your Class Properties as Optional

We can also quickly solve this error by declaring our class data member/property as an option, as you can see in the following code.

class SampleViewController: UIViewController {
    var name: String?
}

3. Add Constructor to your Class

The third solution is to add a constructor to the class. Still, in that constructor, we need to initialize our property with some value. In the case of ViewController, we can add a constructor in the following way.

required init?(coder aDecoder: NSCoder) {
        self.username = "Asad"
        super.init(coder: aDecoder)
    }

In the init method, don’t forget to initialize your data members before calling super call, otherwise, you can face the crash.

That’s it.

If you have any questions feel free to ask in the comments section below.

Next

Please share this post:
Native Mobile Application Developer (Android + IOS) having experience in Java, Swift, Kotlin, Objective C, Unity, C#, C/C++, NODE JS & PHP.

Ask a Question

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

%d bloggers like this: