Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struct defined in a function

Tags:

struct

swift

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?

like image 351
6174 Avatar asked Jul 02 '26 20:07

6174


1 Answers

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.

like image 109
Sergey Kalinichenko Avatar answered Jul 05 '26 13:07

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!