Accessing global variable in Swift

后端 未结 3 1620
萌比男神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:38
     func foo(bar:Any) -> Int {
            let a = 20
            if bar is Bar {
                let c = bar as? Bar
                return c!.a
            }
            return a
      }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-18 10:01

    Use the self keyword:

    func foo() -> Int {
        var a = 20;
        return self.a;
    }
    
    0 讨论(0)
提交回复
热议问题