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:
1 2 3 |
init() { // initialization } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
struct Car { var wheels:Int init() { wheels = 4 } } var c = Car() print("Car have \(c.wheels) number of wheels") |
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.
1 2 3 |
deinit() { // Deinitialization } |
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.
1 2 3 4 5 6 7 8 9 10 11 |
class Cricket { var player = "Sachin" init() { print("Sachin is God of Cricket") } deinit { print("Sachin retired in 2013") } } |
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.