Swift中目标C静态变量的类似物是什么?
在Objective C中使用静态变量是非常方便的(静态变量的值在所有函数/方法调用中都保持着,),但是我在Swift中找不到类似的东西 有这样的吗 这是C中静态变量的一个示例:Swift中目标C静态变量的类似物是什么?,swift,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
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;
}
在名为全局变量的文件顶层(任何类之外)声明变量 文件顶层的变量是惰性初始化的!那么你呢 可以将变量的默认值设置为 读取文件,直到您的代码被读取,文件才被真正读取 首先询问变量的值 引用自 更新: 从您的C示例中,您可以通过以下方式实现相同的功能:
var x = 0 //this is global variable
func staticVar() {
x++
println(x)
}
staticVar()
x //1
staticVar()
x //2
staticVar()
x //3
在操场上测试
发件人:
在C和Objective-C中,定义静态常量和变量
作为全局静态变量与类型关联。然而,在斯威夫特,
类型属性作为类型定义的一部分写入,在
类型的外部大括号,并且每个类型属性都显式
作用域为它支持的类型
您可以使用static关键字定义类型属性。对于计算类型
对于类类型的属性,可以使用class关键字
允许子类重写超类的实现。这个
下面的示例显示了存储和计算类型的语法
特性:
注意
上面的计算类型属性示例适用于只读计算类型>属性,但您也可以定义读写计算类型
使用与计算实例相同的语法键入属性
财产
在看到更新的答案后,以下是对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
可能是圣地亚哥的复制品,不是。Objective C中的静态关键字和Swift具有完全不同的含义。
staticFunc() //Static Value of x: 1
staticFunc() //Static Value of x: 2
staticFunc() //Static Value of x: 3