0
0
Swiftprogramming~5 mins

Deinitializers for cleanup in Swift

Choose your learning style9 modes available
Introduction

Deinitializers help clean up resources when an object is no longer needed. They run automatically before the object is removed from memory.

When you want to close a file or network connection automatically.
When you need to release memory or other resources held by an object.
When you want to print a message or log that an object is being destroyed.
When cleaning up temporary data or undoing setup done during the object's life.
Syntax
Swift
deinit {
    // cleanup code here
}

Deinitializers do not take parameters and cannot be called directly.

Each class can have only one deinitializer.

Examples
This deinitializer prints a message when the FileHandler object is destroyed.
Swift
class FileHandler {
    deinit {
        print("Closing file")
    }
}
This deinitializer calls a method to close the network connection before the object is removed.
Swift
class NetworkConnection {
    deinit {
        closeConnection()
    }

    func closeConnection() {
        print("Connection closed")
    }
}
Sample Program

This program creates a Person object inside a function. When the function ends, the object is removed and the deinitializer runs.

Swift
class Person {
    let name: String
    init(name: String) {
        self.name = name
        print("Person \(name) is created")
    }
    deinit {
        print("Person \(name) is being removed")
    }
}

func createPerson() {
    let _ = Person(name: "Alice")
}

createPerson()
print("End of program")
OutputSuccess
Important Notes

Deinitializers only exist in classes, not in structs or enums.

They help prevent resource leaks by cleaning up automatically.

Summary

Deinitializers run automatically before an object is destroyed.

Use them to clean up resources like files or connections.

They do not take parameters and cannot be called manually.