Home > Enterprise >  What is the lifespan of a static variable in Swift?
What is the lifespan of a static variable in Swift?

Time:09-28

Background

I have the following two classes ViewControllerA and ViewControllerB.

class ViewControllerA: UIViewController
{
    ...
}

For the definition of ViewControllerB we also have a static variable.

class ViewControllerB: UIViewController
{
    static var hasSeenTheLightOfDay: Bool = false
    ...
    func viewDidLoad()
    {
        ViewControllerB.hasSeenTheLightOfDay = true
    }
}

Now lets say my iOS application runs in the following fashion:

User Taps App -> UINavigationController -> ViewControllerA -> ViewControllerB ->
                                                                               |
                                                                         User Goes Back
                                                                               |
                                           ViewControllerA <--------------------

For the sake of the question, ViewControllerA does not hold any references to ViewControllerB.

Questions

Could someone walk me through the entire lifecycle of the static variable hasSeenTheLightOfDay?

  1. When does it come into existence?

  2. When does it go out of existence?

  3. Does it retain the value true? or false? or does it flip-flop? If ViewControllerB is inflated/exited multiple times consecutively from ViewControllerA.

CodePudding user response:

You asked:

  1. When does it come into existence?

When you first reference it.

  1. When does it go out of existence?

It doesn’t.

  1. Does it retain the value true? or false? or does it flip-flop? If ViewControllerB is inflated/exited multiple times consecutively from ViewControllerA.

It keeps the value you set. It does not flip-flop.


The Swift Programming Language: Properties says:

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

CodePudding user response:

Static properties in Swift are lazy, which means they are initialized when they are accessed for the first time. They never go out of existence, because there's at least one reference to them, the class itself. And the class doesn't get deallocated, it exists during the lifetime of the application.

However, the retain discussion only makes sense for reference types. In your code hasSeenTheLightOfDay is a struct, which gets copied every time is assigned to other value, or passed as a function argument.

  • Related