How do I use deinit in classes for cleanup?

In Swift, the `deinit` method is used to perform cleanup just before an instance of a class is deallocated. This method can be particularly useful for releasing any resources that the instance may be holding onto, such as file handles, network connections, or other external resources. The `deinit` method is called automatically when an instance is no longer needed and is being removed from memory.

Here’s a simple example to illustrate how to use `deinit` for cleanup in a Swift class:

class ResourceHandler { var resource: String init(resource: String) { self.resource = resource print(""Resource \(resource) initialized."") } deinit { print(""Resource \(resource) is being deinitialized."") // Cleanup code goes here, such as freeing up resources. } } // Usage var handler: ResourceHandler? = ResourceHandler(resource: "FileHandle") // Perform operations with handler... // When handler is set to nil, deinit is called. handler = nil

Swift deinit cleanup memory management classes