Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing global variable in Swift

Tags:

swift

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.

like image 784
Marco Avatar asked Apr 26 '16 07:04

Marco


People also ask

How do I store global variables in Swift?

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.

How do you avoid 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.

What is global function in Swift?

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").

How do you use a variable outside a function in Swift?

"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.


2 Answers

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.

like image 161
Binarian Avatar answered Nov 15 '22 06:11

Binarian


Use the self keyword:

func foo() -> Int {
    var a = 20;
    return self.a;
}
like image 45
Luka Jacobowitz Avatar answered Nov 15 '22 07:11

Luka Jacobowitz