3

I defined a struct in a function, no matter how many times I invoked the function, struct definition seems like always be the first time function invoked.

the code:

    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()

the result is :

  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

I am not familiar with swift, can any body explain why?

2 Answers 2

6

This code snippet illustrates the way the static attributes are initialized in Swift. It shows that static attributes are initialized only once, at the first invocation. Subsequent invocations do not "reassign" the value: you can see that incrementing g has no effect on the value of attr, which remains unchanged.

Sign up to request clarification or add additional context in comments.

1 Comment

Thx, I think I get the answer.
0

simply use instance of the struct and you get the desired result

var g = 0

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

f()
g++
f()
g++
f()

result:

static attr value is 0, g is 0
static attr value is 1, g is 1
static attr value is 2, g is 2

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.