[swift-evolution] Re-initialization of lazy variables?

Karl Wagner razielim at gmail.com
Fri Oct 6 09:25:09 CDT 2017



> On 6. Oct 2017, at 14:49, Spencer Kohan via swift-evolution <swift-evolution at swift.org> wrote:
> 
> Hi all,
> 
> In migrating to swift 4 I've noticed one thing which has changed is there is no longer support for the automatic re-initialization of lazy variables.  
> 
> In swift 3 I could declare a variable like this:
> 
>     lazy var myVar : MyType! = {
>         return makeMyVar()
>     }()
> 
> And then if I wanted that initialization block to be executed again, I could just nullify the variable:
> 
>     self.myVar = nil
> 
> It looks as if this was never intentional, and according to this bug report <https://bugs.swift.org/browse/SR-5172>, and now the nullified variable stay null rather than executing the initialization block a second time.
> 
> Has the possibility been discussed of providing a way to force lazy vars to initialize more than once?  Working with swift 3 I found this behavior to be very useful in some use cases.  For example in computer graphics it's a nice way to handle the generation of assets which only need to be created in the case of some relatively infrequent event, like for instance a window resize.  It seems I'm not alone - the top stack-overflow question <https://stackoverflow.com/questions/25072597/re-initialize-a-lazy-initialized-variable-in-swift> related to re-initializing lazy variables has over 10k views, so I suppose others have found a use case for this functionality as well.
> 
> Cheers,
> Spencer Kohan
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

Yes, the issue has come up before. There is/was a plan to generalise “lazy” as some kind of “property behaviour” which could support more advanced functionality, such as you described. AFAIK it doesn’t have a specific place on the roadmap.

See: https://github.com/apple/swift/blob/master/test/Prototypes/property_behaviors/lazy.swift <https://github.com/apple/swift/blob/master/test/Prototypes/property_behaviors/lazy.swift>

- Karl
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20171006/dda6548b/attachment.html>


More information about the swift-evolution mailing list