Class 'ViewController' has no initializers in swift
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
In Swift, when working with classes, you might encounter the compiler error: "Class 'ViewController' has no initializers." This error typically arises when a class lacks an explicit initializer and has properties that cannot be automatically initialized to a default value. To understand and address this issue, it's essential to delve into the initialization process in Swift and related concepts. Let’s explore these topics in detail.
Understanding Initializers
Initializers are special methods used to set up a class instance by initializing its properties. In Swift, every stored property of a class or a struct must be initialized before an instance of the type is created. There are several key types of initializers:
1. Designated Initializers
These are the primary initializers for a class. They ensure that all properties introduced by the class are initialized before the initialization process ends. They are responsible for calling a designated initializer of the superclass.
2. Convenience Initializers
Convenience initializers are secondary, supporting initializers that provide additional flexibility. They eventually call a designated initializer from the same class.
3. Automatic Initializers
If a class has no custom initializers, Swift provides a default initializer to create a new instance and initializes all properties to default values. However, this is not the case when certain conditions apply.
The Error: "Class 'ViewController' has no initializers"
When the compiler states, "Class 'ViewController' has no initializers," it means your class has properties that lack default initialization, and it doesn't have an explicitly defined initializer.
Common Causes
- Class Properties Without Default Values
- Example:
- Since
titlehas no default value and no designated initializer is provided, this error is triggered. - Constants declared with
letwithout default values must also be initialized in an initializer. - Assign default values to class properties.
- Custom initialize properties with a constructor.
- Make properties optional if they can be
nil. - This approach initializes the property to
nilby default.
titleandpageNumberare initialized through a designated initializer.subTitleis assigned a default value and thus doesn't need explicit initialization during object creation.

