Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access static variables within class in Swift

Tags:

swift

Is ClassName.staticVaribale the only way to access static variable within the class? I want something like self, but for class. Like class.staticVariable.

like image 671
user3537411 Avatar asked Apr 29 '15 19:04

user3537411


People also ask

How do you access static variables?

Static variables can be accessed by calling with the class name ClassName. VariableName. When declaring class variables as public static final, then variable names (constants) are all in upper case. If the static variables are not public and final, the naming syntax is the same as instance and local variables.

Where static variables are stored in Swift?

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

Can we change value of static variable in Swift?

You create static variable by appending static keyword in front of your variable declaration. We will be using playground to explore more. When we define any variable as let, it means it's values cannot be modified, On the other hand if we define any variable as var it means it's values can be modified.

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.


Video Answer


1 Answers

There are two ways to access a static property/method from a non-static property/method:

  1. As stated in your question, you can prefix the property/method name with that of the type:

    class MyClass {     static let staticProperty = 0      func method() {         print(MyClass.staticProperty)     } } 
  2. Swift 2: You can use dynamicType:

    class MyClass {     static let staticProperty = 0      func method() {         print(self.dynamicType.staticProperty)     } } 

    Swift 3: You can use type(of:) (thanks @Sea Coast of Tibet):

    class MyClass {     static let staticProperty = 0      func method() {         print(type(of: self).staticProperty)     } } 

If you're inside a static property/method you do not need to prefix the static property/method with anything:

class MyClass {     static let staticProperty = 0      static func staticMethod() {         print(staticProperty)     } } 
like image 154
ABakerSmith Avatar answered Sep 23 '22 13:09

ABakerSmith