Given this sample Swift code:
var a = 10;
func foo() -> Int {
var a = 20;
return a;
}
How can function foo get access to global
func foo(bar:Any) -> Int {
let a = 20
if bar is Bar {
let c = bar as? Bar
return c!.a
}
return a
}
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.
Use the self
keyword:
func foo() -> Int {
var a = 20;
return self.a;
}