Is ClassName.staticVaribale
the only way to access static variable within the class? I want something like self
, but for class. Like class.staticVariable
.
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.
data segment stores Swift static variables, constants and type metadata.
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.
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.
There are two ways to access a static property/method from a non-static property/method:
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) } }
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) } }
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