0
0
Swiftprogramming~5 mins

Initializers and designated init in Swift

Choose your learning style9 modes available
Introduction

Initializers set up your objects with starting values. Designated initializers are the main way to make sure all parts of your object get proper values.

When you create a new object and want to give it starting values.
When you have a class with multiple properties that all need values.
When you want to make sure your object is fully ready to use after creation.
When you want to customize how an object is created with different starting options.
Syntax
Swift
class ClassName {
    var property1: Type
    var property2: Type

    init(property1: Type, property2: Type) {
        self.property1 = property1
        self.property2 = property2
    }
}

The init method is the initializer.

Designated initializers fully initialize all properties introduced by that class.

Examples
This is a designated initializer setting both name and age.
Swift
class Person {
    var name: String
    var age: Int

    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }
}
Initializer sets brand and gives a default year.
Swift
class Car {
    var brand: String
    var year: Int

    init(brand: String) {
        self.brand = brand
        self.year = 2024
    }
}
Sample Program

This program creates a Rectangle with width and height using a designated initializer. Then it calculates and prints the area.

Swift
class Rectangle {
    var width: Double
    var height: Double

    init(width: Double, height: Double) {
        self.width = width
        self.height = height
    }

    func area() -> Double {
        return width * height
    }
}

let rect = Rectangle(width: 5.0, height: 3.0)
print("Area of rectangle: \(rect.area())")
OutputSuccess
Important Notes

Every property must have a value before the initializer finishes.

Use self to refer to the current object's properties inside the initializer.

Designated initializers ensure your object is fully ready to use.

Summary

Initializers set starting values for new objects.

Designated initializers fully initialize all properties of a class.

Use init methods to create safe, ready-to-use objects.