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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With