Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use deinit?

Tags:

swift

I came across a function called deinit() while reading The Swift Programming Language guide, but I'm still wondering why and when we need to implement it since we don't really need to manage memory.

like image 821
Ayu Avatar asked Jun 03 '14 15:06

Ayu


People also ask

When should I use Deinit in Swift?

Before a class instance needs to be deallocated 'deinitializer' has to be called to deallocate the memory space. The keyword 'deinit' is used to deallocate the memory spaces occupied by the system resources.

Why do we use Deinit?

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.

What is Deinit in IOS?

A deinit() is called immediately before a class instance is deallocated, and it is helpful when you are working with your own resources. For example, if you create a custom class to open a file and write some data to it, you might need close the file before the class instance is deallocated.

Why is Deinit not called?

So the deinit is not called if there is no additional scope.


1 Answers

It's not required that you implement that method, but you can use it if you need to do some action or cleanup before deallocating the object.

The Apple docs include an example:

struct Bank {     static var coinsInBank = 10_000     static func vendCoins(var numberOfCoinsToVend: Int) -> Int {         numberOfCoinsToVend = min(numberOfCoinsToVend, coinsInBank)         coinsInBank -= numberOfCoinsToVend         return numberOfCoinsToVend     }     static func receiveCoins(coins: Int) {         coinsInBank += coins     } }  class Player {     var coinsInPurse: Int     init(coins: Int) {         coinsInPurse = Bank.vendCoins(coins)     }     func winCoins(coins: Int) {         coinsInPurse += Bank.vendCoins(coins)     }     deinit {         Bank.receiveCoins(coinsInPurse)     } } 

So whenever the player is removed from the game, its coins are returned to the bank.

like image 167
Connor Avatar answered Sep 21 '22 06:09

Connor