Home > Net >  Is deinit Guaranteed to be Called When the Program Finishes?
Is deinit Guaranteed to be Called When the Program Finishes?

Time:12-18

I have the following code:

class Problem{
    init(){
        print("Problem init");
    }
    deinit{
        print("Problem deinit");
    }
    
}
var list = Problem();

The output:

Problem init

The following causes the program to call deinit:

class Problem{
    init(){
        print("Problem init");
    }
    deinit{
        print("Problem deinit");
    }
    
}
do {
    var list = Problem();
}

Questions:

  • Why isn't deinit called the first time?
  • Is there a way to guarantee that deinit will always be called for Problem in code that I have not control of how it is written(i.e., user code)?

P.S. I know there is most likely an obvious reason that I, as a programmer that is new to Swift, have overlooked.

CodePudding user response:

It is because of the difference in Scopes between these two example that you create by adding the do-block.

In the first scenario, when that code is ran, an instance of Problem is created (initialized) at a Global Scope (outside of a class or struct definition in Swift) and then it just sits there. The program does not end and it is never de-initialized.

In the second scenario, you create the instance of Problem inside a the do-block, so it's scope is limited to inside that block. When the do-block ends, the instance is dereferenced, and thus de-initialized.

  • Related