[swift-dev] Lazy var and deinit

Chris Lattner clattner at apple.com
Sun Apr 24 15:57:28 CDT 2016

> On Apr 21, 2016, at 2:29 AM, Alexandr.moq via swift-dev <swift-dev at swift.org> wrote:
> Should SWIFT initialize a variable in deinit method if it has not been initialized? 
> For example: 
> ```swift
> class A {
> 	lazy var b = B()
> 	deinit {
> 		b.clean()
> 	}
> }
> var a = A()
> a.b.doSomething() //1: variable was created
> a = A() //2: "clean" method was called for "b" variable
> a = A() //3: instance of A from step 2 should killed and "deinit" method is called. In this method "b" variable will be created, "clean" will be called and "b" will be killed. So, is it ok or better if swift doesn’t create lazy variables in deinit if variable is not created yet
> ```

I’m not exactly sure what the question is here, but the correct behavior in this case is for the call to “b.clean()” to trigger the lazy initialization of b if it hasn’t already been initialized.  There is no “short circuit” that would prevent this from happening just because this is a deinit.

Also, it is frequently requested, but there is currently no way to check to see if a lazy property has been touched or not.


More information about the swift-dev mailing list