override a private static property on a subclass in swift

In Swift, we cannot directly override a private property or method in a subclass. However, we can achieve similar behavior by creating a computed property with a getter and setter that accesses and modifies the private property in the superclass.

Here is an example:

main.swift
class Superclass {
    private static var myProperty: String = "Hello"

    class var property: String {
        get {
            return myProperty
        }
        set {
            myProperty = newValue
        }
    }

}

class Subclass: Superclass {
    override class var property: String {
        get {
            return super.property + " World!"
        }
        set {
            // modify the property in the superclass
            super.property = newValue
        }
    }
}

// accessing the property on the superclass
print(Superclass.property)  // output: "Hello"

// modifying the property on the superclass
Superclass.property = "Hola"
print(Superclass.property)  // output: "Hola"

// accessing the property on the subclass
print(Subclass.property)  // output: "Hola World!"

// modifying the property on the subclass
Subclass.property = "Bonjour"
print(Subclass.property)  // output: "Bonjour World!"
924 chars
40 lines

In the example above, we have a superclass called Superclass with a private static property called myProperty. We create a computed property called property with a getter and setter that accesses and modifies the private property in the superclass.

Then we create a subclass called Subclass and override the property computed property to modify its behavior. We can still access and modify the private property in the superclass by using super.property.

Finally, we demonstrate how to access and modify the property on both the superclass and the subclass.

gistlibby LogSnag