Accessing global variable in Swift

后端 未结 3 1649
萌比男神i
萌比男神i 2021-01-18 09:34

Given this sample Swift code:

var a = 10;

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

How can function foo get access to global

3条回答
  •  攒了一身酷
    2021-01-18 09:58

    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. . Just like the global Swift functions are implicit a call to Swift., like Swift.print("...").

    var a = 10;
    
    func foo() -> Int {
        let a = 20;
        Swift.print(test.a) // same as print(test.a)
    
        return a;
    }
    
    test.foo() // same as foo()
    

    Output is:

    10


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

提交回复
热议问题