class Foo {
let fooValue = 1
}
print(Foo.fooValue) // not work
class Bar {
static let barValue = 1
}
print(Bar.barValue) // work; print "1"
Why? I expected that Foo example to work, because the value of fooValue is constant, value and memory address known in compilation time. But I need use keyword static to work.
fooValue is an instance property. There's one separate fooValue per every instance (object) of the Foo class.
barValue is a static property. There's one shared barValue that belongs to the class.
Here's a more concrete example. Suppose I had this class:
class Human {
static let numberOfLimbs = 4
let name: String
}
What would you expect to happen if I asked you what the name of a Human is? I.e. Human.name. Well, you wouldn't be able to answer me, because there's no one single name of all humans. Each human would have a separate name. You could however, tell me the number of limbs humans have, (Human.numberOfLimbs), which is (almost) always 4.
you don't have to instantiate your class to access static properties
if you wanted to access it in your first class use
Foo().fooValue
generally you want to use static for properties that you want to access without having to instantiate the object every time
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With