什么是Swift中Objective C静态变量的类比?

Shm*_*idt 3 swift

在Objective C中使用静态变量非常方便(在所有函数/方法调用中都保持静态变量的值),但是我在Swift中找不到这样的东西.

有这样的事吗?

这是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;
}
Run Code Online (Sandbox Code Playgroud)

Soh*_*mon 5

看到更新后的答案后,这是对Objective-C代码的修改:

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

    myStruct.x++
    println("Static Value of x: \(myStruct.x)");
}
Run Code Online (Sandbox Code Playgroud)

打电话是你班上的任何地方

staticFunc() //Static Value of x: 1
staticFunc() //Static Value of x: 2
staticFunc() //Static Value of x: 3
Run Code Online (Sandbox Code Playgroud)