override a private property on a subclass in swift

In Swift, we can't directly override a private property even in a subclass. Because private properties are only accessible within the same class where they were declared. However, we can use Computed Properties to override the behavior of that property.

Here is an example on how to override a private property on a Subclass in Swift:

main.swift
class Parent {
    private var name: String
    
    init(name: String) {
        self.name = name
    }
    
    func printName() {
        print("Parent's name is \(name)")
    }
}

class Child: Parent {
    override var name: String {
        get { return "My name is \(super.name)" }
        set { super.name = newValue }
    }
}

let p = Parent(name: "John")
p.printName() // prints "Parent's name is John"

let c = Child(name: "Sarah")
c.printName() // prints "Parent's name is My name is Sarah"
502 chars
25 lines

In this example, we have a Parent class with a private property name. We can't access this property outside of the Parent class. Then, we create a Child class which inherits from Parent.

We can't directly override the name property in Child because it's private. Instead, we create a Computed Property with the same name but with explicit get/set methods. Inside the get method, we can use super.name to access the original implementation of name from the parent class, and append "My name is " to it. The set method simply calls super.name = newValue to set the value on the parent class.

Now, if we create an instance of Child and call the printName() method, it will override the name property with our computed property and print "Parent's name is My name is Sarah".

gistlibby LogSnag