Uploaded image for project: 'Swift'
  1. Swift
  2. SR-1178

Closure for initializing static variables is evaluated even when the variable is set with a different value

    XMLWordPrintable

    Details

    • Type: Bug
    • Status: Open
    • Priority: Medium
    • Resolution: Unresolved
    • Component/s: None

      Description

      When defining and evaluating a closure to initialize a variable, i.e.

      var name: String = { /* some initialization */ }()
      

      to initialize a static variable, the closure is evaluated even if the variable is only set.

      As a minimal example, this code will print "static"

      Static var (reproduces)
      class Foo {
          static var bar: String = {
              print("static")
              return "Default"
          }()
      }
      
      Foo.bar = "Set"
      

      This differs from the behavior of lazy instance variables. The following code (note lazy instead of static) does not evaluate the closure and doesn't print anything.

      Lazy var (does not reproduce)
      class Foo {
          lazy var baz: String = {
              print("lazy")
              return "Lazy"
          }()
      }
      
      let foo = Foo()
      foo.baz = "Set"
      

        Attachments

          Activity

            People

            • Assignee:
              Unassigned
              Reporter:
              ronnqvist David Rönnqvist
            • Votes:
              0 Vote for this issue
              Watchers:
              3 Start watching this issue

              Dates

              • Created:
                Updated: