[Swift] What I found by using the static property (static)

Introduction

This time, I tried to move the instance property together to understand the static property, so I hope I can deepen my understanding while comparing.

Description of the code I tried

Prepare instance property a and static property b for comparison. The get function is for displaying changes in the values ​​of a and b.

struct Sample {
    var a = 0
    static var b = 0
    
    func get() -> String {
        return "a is\(a), B\(Sample.b)"
    }
}

I tried changing the instance property a

//Create three types of instances.
var S1 = Sample()
var S2 = Sample()
var S3 = Sample()

//Of course the result is the same.
S1.get()  //"a is 0, b is 0"
S2.get()  //"a is 0, b is 0"
S3.get()  //"a is 0, b is 0"

//Let's make changes only for S2.
S2.a = 3   

//S2.Only part a has changed.
S1.get()  //"a is 0, b is 0"
S2.get()  //"a is 3 and b is 0"
S3.get()  //"a is 0, b is 0"
//When trying to access the variable a, S1.a or S2.a or S3.Become a.
//Since it is accessed in association with the instantiated one, if the value is changed, it will be changed for each instance.
//Even if you look at the result, S2.You can see that only a has been changed.

I tried changing the static property b

Sample.b = 6  

//All b have changed.
S1.get()  //"a is 0, b is 6"
S2.get()  //"a is 3 and b is 6"
S3.get()  //"a is 0, b is 6"
//To access the static property b, Sample.Become b. S1.You cannot access b.
//You can see that it is a property associated with the original type itself, not the instance.
//Even if you look at the change result, you can see that all the values ​​have been changed because the contents of the original type have been changed.

Recommended Posts

[Swift] What I found by using the static property (static)
What I learned through the swift teacher
I tried to build the environment little by little using docker
[Swift] Hit the API using Decodable / Generics
I tried using Realm with Swift UI
[Swift] Termination of the program by assertion
I tried using Docker for the first time
[Swift] Various things I learned by implementing Realm
[API] I tried using the zip code search API
[Swift] Termination of the program by the fatalError function
I tried using the profiler of IntelliJ IDEA
I tried to investigate the mechanism of Emscripten by using it with the Sudoku solver