swift - Swift 中 Objective C 静态变量的模拟是什么?

标签 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;
}

最佳答案

在看到您更新的答案后,这里是您的 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/

相关文章:

swift - socket 无法连接到重复内容 UIImageView 错误?

swift - 在 Swift 中模拟 String 类方法

swift - fatal error : unexpectedly found nil while unwrapping an Optional value: Swift, 核心数据

swift - 为什么这一行 NSNotificationCenter.defaultCenter().postNotificationName(...) 抛出 SIGABRT

ios - 根据传入的值显示大量文本

ios - 如何在 Swift 中隐藏继承的方法

ios - 无法将类型 'String' 的值转换为预期的参数类型 'NSManagedObject' Swift

ios - 在 Alamofire 闭包中返回 Bool

ios - 如何识别 Xcode UI 测试中的控制中心元素?

xcode - 如何在每次使用类时快速运行一个方法