Marco Marco - 6 months ago 5x
Swift Question

Accessing global variable in Swift

Given this sample Swift code:

var a = 10;

func foo() -> Int {
var a = 20;
return a;

How can function foo get access to global variable a with value 10 instead of the local a with value 20?

Please note that both a and foo are not declared inside a class but in a generic module. I am looking for a way to tell Swift to access globally defined a var instead of the locally defined one.


I created a project in Xcode, a console application, the target is here a module. So I named the project test and the target has the same name so in the project the module itself has also the name test. Any global definition will be implicit a call to test. .

var a = 10;

func foo() -> Int {
    let a = 20;

    return a;
} // same as foo()

Output is:


So you have to add the module name before the variable to get the global one and not the local one overshadowing it.