Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use Initializers in Swift
Written by Team Kodeco

Initializers in Swift are special methods that are used to create new instances of a class or structure. They are responsible for setting up the initial state of an object when it’s first created.

Here’s an example of how to define an initializer in a class:

class MyClass {
  var myProperty: Int
  
  init(propertyValue: Int) {
    self.myProperty = propertyValue
  }
}

This creates a new class called “MyClass” with an initializer that takes one parameter called “propertyValue” and sets the value of the “myProperty” property to the value of the parameter.

You can create a new instance of the class using the initializer like this:

let myObject = MyClass(propertyValue: 10)

Here’s an example of how to define an initializer in a structure:

struct Point {
  var x: Double
  var y: Double

  init(x: Double, y: Double) {
    self.x = x
    self.y = y
  }
}

This creates a new structure called “Point” with an initializer that takes two parameters called “x” and “y” and sets the values of the corresponding properties to the values of the parameters.

You can create a new instance of the structure using the initializer like this:

let myPoint = Point(x: 1.0, y: 2.0)

Default initializer

As long as all of your properites have default values, Swift provides a default initializer if no initializer is defined.

For example, in the following class definition:

class MyClass {
  var myProperty: Int = 0
}

You can create a new instance of the class without providing any parameters because the default value of 0 is already set for the myProperty property.

let myObject = MyClass()

Designated and Convenience Initializers

In addition to the default initializer, you can also define multiple initializers for a class or structure, and these are called designated initializers and convenience initializers.

A designated initializer is the main initializer for a class or structure, and it’s responsible for fully initializing all the properties of the class or structure.

A convenience initializer is a secondary initializer that can call a designated initializer with default or specific values. Convenience initializers are useful for providing a simpler or more convenient way to create an instance of a class or structure.

Here’s an example of a designated initializer and a convenience initializer for a class:

class MyClass {
  var myProperty: Int

  init(propertyValue: Int) {
    self.myProperty = propertyValue
  }

  convenience init() {
    self.init(propertyValue: 0)
  }
}

Here the init(propertyValue: Int) is the designated initializer and convenience init() is the convenience initializer. The convenience initializer calls the designated initializer with a default value of 0.

© 2024 Kodeco Inc.