Access to a global variable in Swift

Given this example Swift code:

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

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

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

+5
source share
3 answers

I created a project in Xcode, a console application, the goal here is a module. Therefore, I called the project test , and the target has the same name, so in the project the module itself also has the name test . Any global definition will be an implicit call to test. . Just as global Swift functions are an implicit Swift. call Swift. e.g. 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:

ten


So, you must add the module name in front of the variable in order to get global, not local, shading it.

+3
source

Use the self keyword:

 func foo() -> Int { var a = 20; return self.a; } 
+2
source
  func foo(bar:Any) -> Int { let a = 20 if bar is Bar { let c = bar as? Bar return c!.a } return a } 
+2
source

Source: https://habr.com/ru/post/1247916/


All Articles