Swift Initialization and Deinitialization Example

1. Introduction

Initialization and deinitialization are essential aspects of object-oriented programming in Swift. Initialization ensures that an object is ready for use by setting its initial state, while deinitialization allows an object to free up any resources before it's destroyed. Let's delve deeper into these concepts with an example.

2. Source Code Example

class CoffeeMachine {
    let brand: String
    var coffeeMade: Int

    // Initializer
    init(brand: String) {
        self.brand = brand
        self.coffeeMade = 0
        print("\(brand) coffee machine is ready!")
    }

    // Deinitializer
    deinit {
        print("\(brand) coffee machine is being deinitialized after making \(coffeeMade) cups of coffee!")
    }

    func makeCoffee() {
        coffeeMade += 1
        print("Coffee made! Total \(coffeeMade) cups made by \(brand).")
    }
}

func useCoffeeMachine() {
    let myCoffeeMachine = CoffeeMachine(brand: "CafeBrew")
    myCoffeeMachine.makeCoffee()
    myCoffeeMachine.makeCoffee()
}

useCoffeeMachine()

Output:

CafeBrew coffee machine is ready!
Coffee made! Total 1 cups made by CafeBrew.
Coffee made! Total 2 cups made by CafeBrew.
CafeBrew coffee machine is being deinitialized after making 2 cups of coffee!

3. Step By Step Explanation

1. Class Declaration:

- We've declared a CoffeeMachine class, which has two properties: brand and coffeeMade.

- The brand is constant (let), implying that once set during initialization, it cannot be changed.

- The coffeeMade property tracks the number of coffees made by the machine.

2. Initializer:

- The init method is a special method called an initializer. It sets the initial state for the object when it's created.- In our example, we pass the brand of the coffee machine during initialization. The coffeeMade is initialized to 0, indicating no coffee has been made yet.- The print statement inside the init method demonstrates that the coffee machine is ready for use.

3. Deinitializer:

- The deinit method is another special method that's called just before an instance of the class is deallocated.

- This method is useful for cleaning up, like releasing file resources, network connections, or any cleanup related task.

- In our example, the deinit method prints a farewell message, mentioning the brand and the total number of coffees made.

4. makeCoffee Method:

- This method simulates the action of the coffee machine making a cup of coffee.

- Each time this method is called, the coffeeMade count is increased by 1.

5. Function to Use the CoffeeMachine:

- We define a function, useCoffeeMachine, where we create an instance of the CoffeeMachine class and make coffee twice.

- Since the myCoffeeMachine instance is local to the function, it will be deallocated once the function completes its execution. This will trigger the deinit method. 

In this blog post, we've seen how to set up initialization for objects to ensure they're in a valid state before use, and how to perform cleanup tasks before an object is deallocated. These concepts are pivotal in resource management and efficient programming in Swift.


Comments