There are some posts for how to write code for static constant
and static variable
in Swift. But it is not clear when to use static constant
and static variable
rather than constant
and variable
. Can someone explain?
The Static keyword makes it easier to utilize an objects properties or methods without the need of managing instances. Use of the Static keyword in the Singleton pattern can reduce memory leaks by mismanaging instances of classes.
Static variables are used to keep track of information that relates logically to an entire class, as opposed to information that varies from instance to instance.
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.
Every useful program needs to store data at some point, and in Swift there are two ways to do it: variables and constants. A variable is a data store that can have its value changed whenever you want, and a constant is a data store that you set once and can never change.
When you define a static var/let into a class (or struct), that information will be shared among all the instances (or values).
class Animal { static var nums = 0 init() { Animal.nums += 1 } } let dog = Animal() Animal.nums // 1 let cat = Animal() Animal.nums // 2
As you can see here, I created 2 separate instances of Animal
but both do share the same static variable nums
.
Often a static constant is used to adopt the Singleton pattern. In this case we want no more than 1 instance of a class to be allocated. To do that we save the reference to the shared instance inside a constant and we do hide the initializer.
class Singleton { static let sharedInstance = Singleton() private init() { } func doSomething() { } }
Now when we need the Singleton
instance we write
Singleton.sharedInstance.doSomething() Singleton.sharedInstance.doSomething() Singleton.sharedInstance.doSomething()
This approach does allow us to use always the same instance, even in different points of the app.
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