16

How are static variables in Swift stored?

  1. What happens if I never call the func useStaticVar() ? Are these variables initialised or not?

  2. What happens if I do call useStaticVar() and then never access them again? Ar

    struct Something {
        static var myVariable = 0
        static let myConstant = 3
        static var myString: String?
    
        static func useStaticVar() {
            myVariable = myConstant
            myString = String(myVariable)
        }
    }
    
Esqarrouth
  • 38,543
  • 21
  • 161
  • 168

2 Answers2

3

Check this: Type Properties

NOTE

Unlike stored instance properties, you must always give stored type properties a default value. This is because the type itself does not have an initializer that can assign a value to a stored type property at initialization time.

Stored type properties are lazily initialized on their first access. They are guaranteed to be initialized only once, even when accessed by multiple threads simultaneously, and they do not need to be marked with the lazy modifier.

you must always give stored type properties a default value.

Your code lacks a default value for myString, in such cases, Swift give it a default nil.

Stored type properties are lazily initialized on their first access.

You can test and see how stored type properties are initilized with some code like this:

func ZeroGenerator() -> Int {
    print(#function)
    return 0
}

func ThreeGenerator() -> Int {
    print(#function)
    return 3
}

func NilGeneartor() -> String? {
    print(#function)
    return nil
}

struct Something {
    static var myVariable = ZeroGenerator()
    static let myConstant = ThreeGenerator()
    static var myString: String? = NilGeneartor()

    static func useStaticVar() {
        print(#function)
        myVariable = myConstant
        myString = String(myVariable)
    }
}

Something.useStaticVar()

Output:

useStaticVar()
ZeroGenerator()
ThreeGenerator()
NilGeneartor()

Compiler may make some optimizations for constant default values, but semantically no difference.

OOPer
  • 47,149
  • 6
  • 107
  • 142
  • Actually a clearer way to illustrate this is just print the static vars but call them multiple times. You'll see 1. that they are not called before they are accessed (lazy), and 2. that they are only called once and are stored (globally) once they are accessed the first time. So 2 makes them different than lazy instances which do not have 2 but share 1. – SmileBot Dec 06 '22 at 20:29
1
static var myVariable = 0
static let myConstant = 3

Are initialized. myString is initialized in func useStaticVar. If you don't call it it will remain nil, because it is optional. static methods cannot be overrided. Some intresting information is here.

Community
  • 1
  • 1
katleta3000
  • 2,484
  • 1
  • 18
  • 23