What does init() do in Swift?


The init() method in Swift is used to initialize the objects of a class. When an object is created using the function Object() { [native code] } of the class, it is automatically called and establishes the object's initial state. To offer customized initialization behavior, such as establishing default values for properties or carrying out other setup chores, the init() method can be changed.

Without returning any values, the function is sometimes used to initialize objects with some values. The class's designated initializer, the init() method, should be used to create objects of that class.

Here is an example of a simple init() 

In this example, you will create a class with some properties. To provide the default values to the properties, you can create an initializer without arguments.

Example 

class Person {
    
   var firstName: String
   var lastName: String
   var age: Int
   init() {
      self.firstName = ""
      self.lastName = ""
      self.age = 0
   }
}

In this example, the init() method is used to initialize the firstName, lastName, and age properties with default values of an empty string and 0, respectively.

You can create an object of the class by calling the constructor −

let person = Person()

The init() method will be called automatically, and the properties of the person object will be initialized with the default values.

Here is another example of init() with parameters

In this example, you will create a class with some properties. To provide the initial values to the properties, you can create an initializer with arguments.

Example 

class Person {
    
   var firstName: String
   var lastName: String
   var age: Int
    
   init(firstName: String, lastName: String, age: Int) {
      self.firstName = firstName
      self.lastName = lastName
      self.age = age
   }
}

In this example, the init() method takes three parameters: firstName, lastName, and age.

You can create an object of the class by calling the constructor with the parameters

let person = Person(firstName: "Amit", lastName: "Sharma", age: 30)

The init(firstName:lastName:age:) method will be called automatically, and the properties of the person object will be initialized with the values passed to the constructor.

You can also provide default values for the parameters of the init() method

class Person {
    
   var firstName: String
   var lastName: String
   var age: Int
    
   init(firstName: String = "", lastName: String = "", age: Int = 0) {
      self.firstName = firstName
      self.lastName = lastName
      self.age = age
   }
}

In this scenario, you can create an object of the class by calling the constructor without any parameters. The properties will be initialized with default values.

let person = Person()

The init() method will be called automatically, and the properties of the person object will be initialized with the default values.

There are few things that we need to keep in mind while working with init() method

  • “Overloading” of the initializer is a case when a class has multiple initializers and each of them has different parameters,

  • The majority of the initializer work is done by convenience initializer when it calls another initializer called as “designated” initializer. When the underlying implementation of the class is the same but there are multiple ways to initialize it, we use a convenience initializer.

Example

Here is an example of a class with a designated initializer and a convenience initializer −

class Person {
    
   var firstName: String
   var lastName: String
   var age: Int
    
   init(firstName: String, lastName: String, age: Int) {
      self.firstName = firstName
      self.lastName = lastName
      self.age = age
   }
    
   convenience init(firstName: String) {
      self.init(firstName: firstName, lastName: "", age: 0)
   }
}

In this example, the init(firstName:lastName:age:) method is the designated initializer, and init(firstName:) is the convenience initializer.

You can create an object of the class by calling the designated initializer

let person = Person(firstName: "John", lastName: "Doe", age: 30)

You can also create an object of the class by calling the convenience initializer

let person = Person(firstName: "John")

In this example, the convenience initializer calls the designated initializer and passes the default values for lastName and age.

Additionally, Automatic Initializer Inheritance is a feature of Swift. This implies that a class will automatically inherit all of the designated initializers of its superclass if it does not define any of its own unique initializers.

Here are some advantages of using the init() method in Swift −

  • Consistency − Initializing an object with the init() method ensures that all objects of a class have a consistent initial state.

  • Customization − The init() method can be overridden to provide custom initialization behavior. This allows you to set default values for properties, perform other setup tasks, or even validate the input parameters.

  • Multiple Initializers − A class can have multiple initializers, each with different parameters, which allows you to provide different ways to create an object of a class.

  • Convenience Initializer − A class can have convenience initializers, which call for another initializer to perform the majority of the initialization work.

  • Automatic Initializer Inheritance − Automatic Initializer Inheritance is a feature of Swift that allows classes to automatically inherit all of their superclass's designated initializers if they don't define any of their own custom initializers.

  • Memory Management − Initializing an object with the init() method ensures that the object is properly allocated and initialized in memory.

  • Type Safety − Swift uses type safety, and the init() method is used to ensure that an object is of the correct type.

  • Encapsulation − The implementation details of an object might be contained in the init() method, making it more challenging for other code to construct the object in an incorrect state.

  • Improved Readability − By using the init() method, the code becomes more readable and maintainable, as it clearly indicates that an object is being created and initialized.

  • It is a must-have − the init() method is the designated initializer for a class, and it is necessary for creating an object of that class. It is called automatically when an object is created using the class's constructor.

Conclusion

An object of a class in Swift can be initialized and have its initial state set using the init() method. When an object is created by executing the function for the class, it is automatically invoked. It can be customized to offer unique initialization behavior.

The init() function is a must in every class because it allows developers to guarantee that all objects of a class have a consistent initial state, offers multiple ways to create an object, encapsulates the implementation details, and makes code easier to read and maintain. Overall, the init() method is a strong tool that aids developers in writing Swift code that is well-structured, reliable, and manageable.

Updated on: 28-Feb-2023

357 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements