Swift Deinitializers
Cleanup code that runs when instances are deallocated
๐งน What are Deinitializers?
Deinitializers are called automatically just before a class instance is deallocated. They perform cleanup tasks like closing files, releasing resources, or saving data before the instance is destroyed from memory.
class FileManager {
var fileName: String
init(fileName: String) {
self.fileName = fileName
print("Opening file: \(fileName)")
}
deinit {
print("Closing file: \(fileName)")
// Cleanup code here
}
}
func createFile() {
let file = FileManager(fileName: "document.txt")
// File will be automatically closed when function ends
}
createFile()
Output:
Opening file: document.txt
Closing file: document.txt
Key Deinitializer Concepts
Automatic
Called automatically when instance is deallocated
deinit {
// Cleanup code
print("Instance destroyed")
}
Cleanup
Perfect place for resource cleanup
deinit {
file.close()
connection.disconnect()
}
Classes Only
Only available for class types, not structs
class MyClass {
deinit {
// Valid
}
}
No Parameters
Deinitializers take no parameters
deinit {
// No parameters allowed
cleanup()
}
๐น Basic Deinitializer Example
Here's a simple example showing when deinitializers are called:
class Player {
var name: String
var score: Int
init(name: String) {
self.name = name
self.score = 0
print("\(name) joined the game")
}
deinit {
print("\(name) left the game with score: \(score)")
}
func addPoints(_ points: Int) {
score += points
}
}
func playGame() {
let player = Player(name: "Alice")
player.addPoints(100)
// player is deallocated when function ends
}
playGame()
print("Game session ended")
Output:
Alice joined the game
Alice left the game with score: 100
Game session ended
๐น Resource Management Example
Deinitializers are commonly used for resource management:
class DatabaseConnection {
var isConnected: Bool = false
let serverName: String
init(serverName: String) {
self.serverName = serverName
connect()
}
func connect() {
isConnected = true
print("Connected to \(serverName)")
}
func disconnect() {
if isConnected {
isConnected = false
print("Disconnected from \(serverName)")
}
}
deinit {
disconnect()
print("Database connection cleaned up")
}
}
func performDatabaseOperation() {
let db = DatabaseConnection(serverName: "MainServer")
// Perform database operations
print("Performing database operations...")
// Connection automatically cleaned up when function ends
}
performDatabaseOperation()
Output:
Connected to MainServer
Performing database operations...
Disconnected from MainServer
Database connection cleaned up