To add a getter to a subclass in Swift, you can override the getter of a property of the superclass.
Let's say you have a superclass called Person
, with a property name
. Here's how you can add a getter to a subclass called Student
.
main.swift286 chars18 lines
In this example, the Student
subclass overrides the name
property, and adds (Student)
to the original name returned by the super class getter.
Note that we also have to override the set
property, or we won't be able to set the name on an instance of Student
. In this case, we're just calling the super
setter, to preserve the original behavior.
That's it! With this code, you can now create instances of Student
, and access their name
property, which will have the additional (Student)
string.
gistlibby LogSnag