Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
    }  
like image 985
Nicolas Miari Avatar asked Feb 27 '16 04:02

Nicolas Miari


People also ask

Can we override properties in Swift?

Classes in Swift can call and access methods, properties, and subscripts belonging to their superclass and can provide their own overriding versions of those methods, properties, and subscripts to refine or modify their behavior.

Can we override method in extension?

Extension methods cannot be overridden the way classes and instance methods are. They are overridden by a slight trick in how the compiler selects which extension method to use by using "closeness" of the method to the caller via namespaces.

Can we override method in extension Swift?

If a protocol defines a method, and provides a default implementation in an extension, a class can override that method, and the override will be called for any reference to the instance, even if the reference's type is declared as the protocol.

What is method overriding in Swift?

This allows subclasses to directly access the superclass members. Now, if the same method is defined in both the superclass and the subclass, then the method of the subclass class overrides the method of the superclass. This is known as overriding.


1 Answers

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
like image 179
matt Avatar answered Oct 20 '22 22:10

matt