What is the main difference between "static var" and "var" in Swift? Can someone explain this difference to me, possibly with a little example?
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.
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.
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.
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.
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
.
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