Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does swift have class level static variables? [duplicate]

How to declare static constant in class scope? such as

class let Constant: Double = 3.1415926 // I know that in class we use class modifier instead of static. 
like image 517
tounaobun Avatar asked Nov 07 '14 15:11

tounaobun


People also ask

Can static members of a class have multiple copies?

Static variables in a class: As the variables declared as static are initialized only once as they are allocated space in separate static storage so, the static variables in a class are shared by the objects. There can not be multiple copies of same static variables for different objects.

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.

Where static variables are stored in Swift?

data segment stores Swift static variables, constants and type metadata.

What are static variables 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.


1 Answers

Swift supports static type properties, including on classes, as of Swift 1.2:

class MyClass {     static let pi = 3.1415926 } 

If you need to have a class variable that is overridable in a subclass, you'll need to use a computed class property:

class MyClass {     class var pi: Double { return 3.1415926 } }  class IndianaClass : MyClass {     override class var pi: Double { return 4 / (5 / 4) } } 
like image 75
Nate Cook Avatar answered Sep 20 '22 09:09

Nate Cook