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.swift502 chars25 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