Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between "static var" and "var" in Swift

Tags:

var

static

swift

What is the main difference between "static var" and "var" in Swift? Can someone explain this difference to me, possibly with a little example?

like image 269
Alec Avatar asked Dec 01 '14 09:12

Alec


People also ask

What is difference between static let and static VAR in Swift?

As you can see, the constant Static let declared can be accessed by it's type, but cannot be changed. The Static var declared can not only be accessed by it's type but also can be modified. Consequently, all the future instances will be changed.

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

Static variables are those variables whose values are shared among all the instance or object of a class. When we define any variable as static, it gets attached to a class rather than an object. The memory for the static variable will be allocation during the class loading time.

What's the difference between static and class keywords in Swift?

But what's the difference? The main difference is static is for static functions of structs and enums, and class for classes and protocols. From Chris Lattner the father of Swift. We considered unifying the syntax (e.g. using “type” as the keyword), but that doesn't actually simply things.


1 Answers

static var belongs to type itself while var belongs to instance (specific value that is of specific type) of type. For example:

struct Car {
    static var numberOfWheels = 4
    var plateNumber: String
}

Car.numberOfWheels = 3
let myCar = Car(plateNumber: "123456")

All cars has same amount of wheels. An you change it on type Car itself.

In order to change plate number you need to have instance of Car. For example, myCar.

like image 69
Kirsteins Avatar answered Oct 23 '22 14:10

Kirsteins