Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is analogue of Objective C static variable in Swift?

Tags:

swift

It was very convenient to have static variables in Objective C (static variable's value is maintained throughout all function/method calls), however I couldn't find anything like this in Swift.

Is there anything like this?

This is an example of static variable in C:

void func() {
    static int x = 0; 
    /* x is initialized only once across four calls of func() and
      the variable will get incremented four 
      times after these calls. The final value of x will be 4. */
    x++;
    printf("%d\n", x); // outputs the value of x
}

int main() { //int argc, char *argv[] inside the main is optional in the particular program
    func(); // prints 1
    func(); // prints 2
    func(); // prints 3
    func(); // prints 4
    return 0;
}
like image 853
Shmidt Avatar asked Jan 20 '26 16:01

Shmidt


1 Answers

After seeing your updated answer, here is the modification for your Objective-C code:

func staticFunc() {    
    struct myStruct {
        static var x = 0
    }

    myStruct.x++
    println("Static Value of x: \(myStruct.x)");
}

Call is anywhere in your class

staticFunc() //Static Value of x: 1
staticFunc() //Static Value of x: 2
staticFunc() //Static Value of x: 3
like image 195
Sohil R. Memon Avatar answered Jan 23 '26 12:01

Sohil R. Memon