Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Swift, why does assigning to a static variable also invoke its getter

I understand that in Swift, static vars are implicitly lazy: https://stackoverflow.com/a/34667272/1672161

But I'm not clear on why this happens:

protocol HatType {}

class Hat: HatType {
    init() { print("real hat") }
}

class MockHat: HatType {
    init() { print("mock hat") }
}

struct HatInjector {
    static var hat: HatType = Hat()
}

HatInjector.hat = MockHat()

// Output:
// real hat
// mock hat

What I'm seeing is that the assignment to the static var, is also invoking the getter in a sense. This isn't intuitive to me. What is happening here? Why doesn't the assignment only happen?

like image 836
abc123 Avatar asked Apr 12 '17 15:04

abc123


People also ask

What is the use of static variable in Swift?

Static variables are those variables whose values are shared among all the instance or object of a class. When we define any variable as static, it gets attached to a class rather than an object. The memory for the static variable will be allocation during the class loading time.

Can we override static variable in Swift?

Type properties and type methods declared¹ with class can be overridden in subclasses, but ones defined with static cannot.

What's the difference between a static variable and a class variable Swift?

Where static and class differ is how they support inheritance: When you make a static property it becomes owned by the class and cannot be changed by subclasses, whereas when you use class it may be overridden if needed.

Where static variables are stored in Swift?

data segment stores Swift static variables, constants and type metadata.


1 Answers

This is because static and global stored variables are currently (this is all subject to change) only given one accessor by the compiler – unsafeMutableAddressor, which gets a pointer to the variable's storage (this can be seen by examining the SIL or IR emitted).

This accessor:

  1. Gets a pointer to a compiler-generated global flag determining whether the static variable has been initialised.

  2. Calls swift_once with this pointer, along with a function that initialises the static variable (this is the initialiser expression you give it, i.e = Hat()). On Apple platforms, swift_once simply forwards onto dispatch_once_f.

  3. Returns a pointer to the static variable's storage, which the caller is then free to read and mutate – as the storage has static lifetime.

So it does more or less the equivalent of the Objective-C thread-safe lazy initialisation pattern:

+(Hat*) hat {

    static Hat* sharedHat = nil;
    static dispatch_once_t oncePredicate;

    dispatch_once(&oncePredicate, ^{
        sharedHat = [[Hat alloc] init];
    });

    return sharedHat;
}

The main difference being that Swift gives back a pointer to the storage of sharedHat (a pointer to a reference), rather than sharedHat itself (just a reference to the instance).

Because this is the one and only accessor for static and global stored variables, in order to perform an assignment, Swift needs to call it in order to get the pointer to the storage. Therefore, if it wasn't initialised already – the accessor needs to first initialise it to its default value (as it has no idea what the caller is going to do with it), before the caller then sets it to another value.

This behaviour is indeed somewhat unintuitive, and has been filed as a bug. As Jordan Rose says in the comments of the report:

This is currently by design, but it might be worth changing the design.

So this behaviour could well change in a future version of the language.

like image 166
Hamish Avatar answered Nov 15 '22 07:11

Hamish