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
<Issues · apple/swift-issues · GitHub, 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
<Re-initialize a lazy initialized variable in Swift - Stack Overflow;
related to re-initializing lazy variables has over 10k views, so I suppose
others have found a use case for this functionality as well.
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.
On 6. Oct 2017, at 14:49, Spencer Kohan via swift-evolution <swift-evolution@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 <Issues · apple/swift-issues · GitHub, 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 <Re-initialize a lazy initialized variable in Swift - Stack Overflow; related to re-initializing lazy variables has over 10k views, so I suppose others have found a use case for this functionality as well.