In this tutorial you will learn about the Swift Deinitialization and its application with practical example.
Swift Deinitialization
Swift is smart enough at memory management, it automatically deallocates an instance and free up occupied resources when instance is no longer needed. Deinitialization is the process which deallocate or freeup occupied memory and other system resource for an instance no longer in use.
In swift, we have special method called deinitializer that can take care of whole deinitialization process. Deinitializer are invoked immediately before a class instance is deallocated.
In swift, an deinitializer can be created by implementing deinit() method with zero parameters, there can be only one deinitializer per class.
Swift Deinitialization Syntax
Following is the syntax of an deinitializer , an instance method with no parameters is created with the deinit keyword.
Syntax:-
1 2 3 4 |
deinit { // Deinitialization stuff come here } |
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
var ctr = 0 class Counter { init() { ctr = ctr + 1; } deinit { ctr = ctr - 1; } } var c: Counter? = Counter() print("W3Adda - Swift Deinitializer ") print(ctr) c = nil print(ctr) |
Output:-