[swift-evolution] [Discussion] Difference between static and lazy variables regarding evaluation of closure

David Rönnqvist david.ronnqvist at me.com
Fri Apr 8 02:36:11 CDT 2016


I noticed a difference between how static and lazy variables evaluate closures and thought that it was a bug:
https://bugs.swift.org/browse/SR-1178
but apparently it’s not.

The difference can be illustrated in a small example. The following code will evaluate the closure for the static variable, even when *setting* the variable, but won’t evaluate the closure for the lazy variable. Thus, it prints “static”, but not “lazy”.

    class Foo {
        static var bar: String = {
            print("static")
            return "Default"
        }()
        
        lazy var baz: String = {
            print("lazy")
            return "Lazy"
        }()
    }

    Foo.bar = "Set"

    let foo = Foo()
    foo.baz = “Set"

I would have thought that neither case should evaluate the closure when setting the variable, since the result from the closure is never used in that case. I don’t feel that strongly about if the closure is evaluated or not. But I would like both types (static and lazy) to behave the same. 

- David


More information about the swift-evolution mailing list