A string defined in a function
I have defined the structure in a function, no matter how many times I have called that function, the structure definition seems to, as always, will be called the first time.
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()
result:
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'm not familiar with swift, can anyone explain why?
source to share
This code snippet illustrates a way to initialize attributes static
in Swift. It shows that attributes are static
initialized only once on the first call. Subsequent calls do not "reassign" the value: you can see that incrementing g
does not affect the value attr
, which remains unchanged.
source to share
just use an instance of the struct and 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