【问题标题】:What is analogue of Objective C static variable in Swift?Swift中Objective C静态变量的类似物是什么?
【发布时间】:2015-08-01 05:07:46
【问题描述】:

在 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;
}

【问题讨论】:

  • @santiago 不是。 Objective C 和 Swift 中的 static 关键字的含义完全不同。

标签: swift


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    在文件的顶层(任何类之外)声明变量,称为全局变量。

    文件顶层的变量是惰性初始化的!那么你 可以将变量的默认值设置为 读取文件,并且在您的代码之前不会真正读取文件 首先询问变量的值。

    来自HERE的参考。

    更新:

    从您的 C 示例中,您可以通过这种方式快速实现相同的目标:

    var x = 0   //this is global variable 
    
    func staticVar() {
        x++
        println(x)
    }
    
    staticVar()
    x                //1
    staticVar()
    x                //2
    staticVar()
    x                //3
    

    在操场上测试。

    来自Apple Document

    在 C 和 Objective-C 中,您可以定义静态常量和变量 作为全局静态变量与类型相关联。然而,在 Swift 中, 类型属性被写为类型定义的一部分,在 类型的外部花括号,并且每个类型属性都是显式的 范围为它支持的类型。

    您使用 static 关键字定义类型属性。对于计算类型 类类型的属性,您可以使用 class 关键字代替 允许子类覆盖超类的实现。这 下面的示例显示了存储和计算类型的语法 属性:

    struct SomeStructure {
    static var storedTypeProperty = "Some value."
    static var computedTypeProperty: Int {
        // return an Int value here
        }
    }
    enum SomeEnumeration {
        static var storedTypeProperty = "Some value."
        static var computedTypeProperty: Int {
            // return an Int value here
        }
    }
    class SomeClass {
        static var storedTypeProperty = "Some value."
        static var computedTypeProperty: Int {
            // return an Int value here
        }
        class var overrideableComputedTypeProperty: Int {
            // return an Int value here
        }
    }
    

    注意

    上面的计算类型属性示例适用于只读计算类型>属性,但您也可以定义读写计算 使用与计算实例相同的语法类型属性 属性。

    【讨论】:

      猜你喜欢
      • 2011-08-27
      • 2012-01-26
      • 1970-01-01
      • 2010-11-06
      • 2014-07-28
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多