在函数中定义的Struct

617*_*174 3 struct swift

我在函数中定义了一个struct,无论我调用该函数多少次,struct definition似乎总是第一次调用函数.

代码:

    var g = 0
    func f() {
        struct InnerStruct{
            static var attr:Int = g
        }
        println("static attr value is \(InnerStruct.attr), g is \(g)")
    }

    f()
    g++
    f()
    g++
    f()
Run Code Online (Sandbox Code Playgroud)

结果是:

  static attr value is 0, g is 0
  static attr value is 0, g is 1
  static attr value is 0, g is 2
  Program ended with exit code: 0
Run Code Online (Sandbox Code Playgroud)

我对swift不熟悉,可以解释一下为什么?

das*_*ght 6

此代码段说明了static在Swift中初始化属性的方式.它显示static在第一次调用时,属性仅初始化一次.后续调用不会"重新分配"该值:您可以看到增量g对值的影响没有影响,该值attr保持不变.