Mysterious Default Value for un-assigned variable

yeah i think this is another 'quirk' of top-level code... this might be a side-effect of the fact that resultBar is being captured before it's declared. you can see this if you wrap the top-level expressions in a do {} block:

enum Bar {
    case a
    case b
}

func foo(bar: Bar, action: () -> Void) -> Bar {
    action()
    return bar
}

do {
    var actionBar: Bar!

    let resultBar = foo(bar: Bar.b) {
        actionBar = resultBar
        print("Assigned")
    }

    print(actionBar == resultBar) // šŸ‘ˆ false
    print(actionBar) // šŸ‘ˆ Optional(DemoProject.Bar.a)
}
bug.swift:14:37: error: closure captures 'resultBar' before it is declared
12 |     var actionBar: Bar!
13 | 
14 |     let resultBar = foo(bar: Bar.b) {
   |         |                           `- error: closure captures 'resultBar' before it is declared
   |         `- note: captured value declared here
15 |         actionBar = resultBar
   |                     `- note: captured here
16 |         print("Assigned")
17 |     }

there are many strange issues like this with top-level code. see here & here for some others.

2 Likes