Swift Deinitialization

Deinitialization is a process to deallocate class instances when they're no longer needed. This frees up the memory space occupied by the system.

We use the deinit keyword to create a deinitializer. For example,

class Race {
  ...

  // create deinitializer
  deinit {
    // perform deinitialization
    ... 
  }
} 

Here, deinit is the deinitializer of the Race class.

Before you learn about deintializers, make sure you know about the Swift Initializer.


Example: Swift Deinitializer

// declare a class
class  Race {
  var laps: Int

  // define initializer
  init() {
    laps = 5
    print("Race Completed")
    print("Total laps:", laps)
  }

  // define deinitializer
  deinit {
    print("Memory Deallocated")
  }
}

// create an instance
var result: Race? = Race()

// deallocate object
result = nil

Output

Race Completed
Total laps: 5
Memory Deallocated

In the above example,

1. We have created a deinitializer inside the Race class.

deinit {
  print("Memory Deallocated")
}

2. Then, we have created an instance of the Race class and assigned it to a Race type variable named result.

// create an instance
var result: Race? = Race()

Here, Race? indicates that result is an optional, so it can store two types of values:

  • values of the Race type.
  • a nil value.

3. Finally, we assign nil to result:

// deallocate instance
result = nil

This deallocates the instance. The deinitializer is called automatically right before the class instance is deallocated. And the statement inside it is executed.

Note:

  • In Swift, we only use deinitializers when we manually want to deallocate instances. Otherwise, Swift automatically does the deallocation.
  • Deinitializers can only be used with classes and not with structs.
  • Each class can only have a single deinitializer.
Did you find this article helpful?