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.
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)"
}
}
//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.
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