Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use static constant and variable in Swift?

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?

like image 804
Mike Avatar asked Jun 08 '16 11:06

Mike


People also ask

When should I use static in Swift?

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.

When should static variables be used?

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.

What's the difference between a static variable and a class variable in 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.

What is the difference between a constant and a variable in Swift?

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.


1 Answers

When you define a static var/let into a class (or struct), that information will be shared among all the instances (or values).

Sharing information

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.

Singleton

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.

like image 195
Luca Angeletti Avatar answered Sep 22 '22 18:09

Luca Angeletti