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

This was something mentioned here:

I just avoid this completely and now put a main() in the main.swift file to call my actual main function, away from weird top level JavaScript, in a new file.

But that's somewhat confusing, if you were to open the src/TargetName folder you would see "Oh, main.swift, that must be the main file" and then when you open it you realise it has one line in it :slight_smile:
It's weird that naming one file in a target differently just breaks the language.

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

3 Likes