I wrote a code block as the following:
class Person{
        let name:String;
        init(name:String){
         self.name = name;
          println("\(name) is being initialized.");
     }
     deinit{
         println("\(name) is being deInitialized.");
    }
 }
var person:Person?;
person = Person(name:"leo");
person = nil;
When initialized,print is ok. When set person to nil,the deinit method is not called.
If you return nil from a failable initializer, init?() , or if you throw an error from a throwing initializer, init() throws , then deinit will not get called. This means you must clean up any manually allocated memory or other resources before you return nil or throw .
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.
The problem is that a playground is not real life. This is just one more reason for not using them (I think they are a terrible mistake on Apple's part). Use a real iOS app project and deinit will be called as expected.
Example from a real project:
class ViewController: UIViewController {
    class Person{
        let name:String;
        init(name:String){
            self.name = name;
            println("\(name) is being initialized.");
        }
        deinit{
            println("\(name) is being deInitialized.");
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        var person:Person?;
        person = Person(name:"leo");
        person = nil;
    }
}
That does what you expect it to do.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With