Confusion about overriding class properties in Swift

I read the Swift docs and searched here, but I'm still not sure how to implement a class hierarchy, where each subclass sets a custom value for the inherited static property; i.e:

  • The base class defines a static property: all instances have the same value.
  • The subclass overrides the static property: all instances have the same value , which is different from the base class.

Is the property saved?

Also, how do I access the value of a property from an instance method (regardless of a particular class) and get the correct value every time? will the following code work?

class BaseClass { // To be overridden by subclasses: static var myStaticProperty = "Hello" func useTheStaticProperty() { // Should yield the value of the overridden property // when executed on instances of a subclass: let propertyValue = self.dynamicType.myStaticProperty // (do something with the value) } 
+6
source share
1 answer

You are so close to being there, except that you cannot override the static property in a subclass - that is what it means to be static . Thus, you will have to use the class property, which means that it must be a computed property - Swift does not have class properties stored.

So:

 class ClassA { class var thing : String {return "A"} func doYourThing() { print(self.dynamicType.thing) } } class ClassB : ClassA { override class var thing : String {return "B"} } 

And let him test it:

 ClassA().doYourThing() // A ClassB().doYourThing() // B 
+10
source

All Articles