在 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;
}
最佳答案
在看到您更新的答案后,这里是您的 Objective-C 代码的修改:
func staticFunc() {
struct myStruct {
static var x = 0
}
myStruct.x++
println("Static Value of x: \(myStruct.x)");
}
类里面的任何地方都可以打电话
staticFunc() //Static Value of x: 1
staticFunc() //Static Value of x: 2
staticFunc() //Static Value of x: 3
关于swift - Swift 中 Objective C 静态变量的模拟是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31758453/