Nicolas Miari
Nicolas Miari

Reputation: 16246

Confusion Regarding Overriding Class Properties in Swift

I have read the Swift docs and searched here, but I still am not sure about how to implement a class hierarchy where each subclass sets custom value for an inherited static property; that is:

  1. Base class defines a static property: all instances share the same value.
  2. Subclass overrides the static property: all instances share the same value, which is different form that of the base class.

Can the property be stored?

Also, How should I access the value of the property from within an instance method (regardless of the particular class), and get the correct value everytime? 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)
    }  

Upvotes: 14

Views: 6553

Answers (1)

matt
matt

Reputation: 534893

You are so close to being there, except that you can't override a static property in a subclass — that is what it means to be static. So you'd have to use a class property, and that means it will have to be a computed property — Swift lacks stored class properties.

So:

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

And let's test it:

ClassA().doYourThing() // A
ClassB().doYourThing() // B

Upvotes: 24

Related Questions