Introduction

The default initializer is the initializer that is created by the compiler when your class is instantiated.

For example, consider the following Person class:

class Person {
      var firstName:String = ""
      var lastName:String = ""
      var email:String = ""
      var group:Int = 0
}

When you create an instance of the Person class, the compiler automatic generates a default initializer for the Person class so that you can create the instance:

var c =  Person ()

All the stored properties in the Person class are initialized to their default values.

If they are not initialized to some values, such as the following, the compiler will complain that the class has no initializer:

class Person {
    var firstName:String
    var lastName:String
    var email:String
    var group:Int
}

To fix this is to initialize each stored property, or to explicitly create an initializer:


class Person {
    var firstName:String
    var lastName:String
    var email:String
    var group :Int

    init() {
        firstName = ""
        lastName = ""
        email = ""
        group = 0
    }
}

In this case, you are creating your own initializer to initialize the values of the stored properties.

This type of initializer is known as a designated initializer, which is discussed in the next section.

Related Topic