Swift Programming – Deinitialization

In this tutorial you’ll learn about deinitialization in Swift. To follow along, it is recommended to have a Mac and the Xcode IDE installed on it. This tutorial makes use of the Xcode playground for compilation of the Swift codes. If you do not have a Mac, you may try using the open-source code editors which support different operating systems such as AtomSublimeText or VSCode.

Deinitialization

You can implement a deinitializer to perform some cleanup before your class instance gets deallocated. Deinitialization is allowed in classes only.

class BankAccount {
    static var currentBalance: Double = 0.0
}

class Transaction {
    var currentBalance: Double
    
    init() {
        currentBalance = BankAccount.currentBalance
    }
    
    func depositMoney(_ amount: Double) {
        currentBalance += amount
    }
    
    func withdrawMoney(_ amount: Double) {
        currentBalance -= amount
    }
    
    deinit {
        BankAccount.currentBalance = currentBalance
    }
}

let transaction = Transaction()
print(transaction.currentBalance)

transaction.depositMoney(20000)
print(transaction.currentBalance)

transaction.withdrawMoney(5000)
print(transaction.currentBalance)

In the example above, we defined a class named BankAccount with one stored property currentBalance of Double type. We defined another class Transaction to withdraw/deposit money. We initialize our stored property currentBalance in our Transaction class with our BankAccount‘s currentBalance. On deinitialization, we update our BankAccount‘s currentBalance with our Transaction‘s currentBalance after all transactions have been made.

Reference

https://docs.swift.org/swift-book/LanguageGuide/Deinitialization.html