Main.swift global var issue

Spent quite a few minutes now before realising that global declaration must be placed before "foo()":

// main.swift

func foo() {
    dict["hello"] = "world" // πŸ›‘ Thread 1: EXC_BAD_ACCESS (code=1, address=0x8)
}

foo()

var dict: [String : String] = [:]

Could we improve it?

  • either make it a compilation error
  • or make it work without crashing
  • if not the above then improve the crash diagnostic to make it more obvious what's going on.

Minimal example:

// main.swift

let x = hello == "world" // πŸ›‘ Thread 1: EXC_BAD_ACCESS (code=1, address=0x18)
var hello = "world"

I think this is a problem because Swift follows a Top-down approach whereby variables must be initialized before usage.
You can also make it a lazy variable too

Yep we’re aware. :slightly_smiling_face: I’ll find some time one of these days.

2 Likes