[swift-evolution] [swift-dev] Lazy var and deinit

John McCall rjmccall at apple.com
Thu Apr 21 11:15:58 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
> ```
> To be honest, I don’t know which topic I should use. Because I don’t know, it’s propose, bug or something else. 

It's probably a question for swift-evolution more than -dev; moving there.

The behavior you're seeing is a product of the current straightforward rule for what it means to access a lazy property.  I think complicating that rule to say something like "direct accesses in deinit produce an optional T instead of calling the initializer" would be... well, defensible, but a poor idea overall.  It would be a better language approach to allow some way to access the underlying optional storage of the property at any point in the program.  That should be easily done with the property behaviors feature when it lands, so I don't think we need anything else here.

John.


More information about the swift-evolution mailing list