Captain Hatteras
Captain Hatteras

Reputation: 519

Is deinit Guaranteed to be Called When the Program Finishes?

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:

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

Upvotes: 1

Views: 120

Answers (1)

jcodes
jcodes

Reputation: 316

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.

Upvotes: 2

Related Questions