Initialization and Deinitialization in Swift

Updated 30 March 2022

Save

Initialization is the process of making an instance of a class, structure, or enumeration to use. This process includes providing an initial value for each stored property on that instance. Initializer performs initialization before creating or using the instance of the class.

Deinitializer is called before deallocation of a class instance which means the allocated memory for the instance of the class is destroyed. You write Deinitializers using the  deinit keyword and the initializers with the init keyword. Deinitializers remove memory only of class types.

Initializers

Initializers are called to allocate memory to the instance of the class so an initializer is like an instance method with no parameters, written using the init keyword:

For example, the example below defines a new structure called Car to store wheels as a variable a car has. Structure Car has one store property, wheels, which is type Int.

The structure defines a single initializer, init, with no parameters, which initializes the stored wheels with a value of 4 (number of wheels a car has).

You can read more about Initializer from this link.

Deinitializers

Swift automatically does the deallocation of your instances if we don’t need them, to free up resources. In addition, swift handles the memory management of instances through automatic reference counting (ARC), as a result, we only use deinitializers when we manually want to deallocate instances.

For example, the example below defines a new class Cricket, to contain player. Class Cricket has one stored property, player, which is of type String.

The class defines an initializer, init, which prints “Sachin is God of Cricket”, and a deinitializer, deinit, which prints “Sachin retired in 2013”. Therefore, the memory will deallocate.

For more details about Deinitializer, click here.

Conclusion

I hope this blog helped you understand the Initialization and Deinitialization in Swift. Know more about initialization and denitialization.

author
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Start a Project


    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home