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.
There's another and efficient way to create and store global variable is using a struct, you should always create a struct and encapsulate all the global variable inside it and can use in any class wherever we want., Let's see how we can do it. This is how we can create global variables in swift.
Global variables that are defined outside of any method or closure can be scope restricted by using the private keyword. A constant ("let") is not a variable.
Swift. Global functions, or functions that can be accessed from anywhere without the scope of a specific type is an old concept that was popular in languages like C and Objective-C, but unrecommended in Swift as we would rather have things that are nicely typed and scoped ("swifty").
"use variables from within the function, outside of the function" You can't. They are declared inside the function. So they are temporary, and scoped within the function. If you want something outside the function, pass it out as part of the result, or (less good) declare it outside the function.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With