add a getter to a subclass in swift

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.swift
class Person {
    var name: String
    init(name: String) {
        self.name = name
    }
}

class Student: Person {
    override var name: String {
        get {
            return super.name + " (Student)"
        }
        set {
            super.name = newValue
        }
    }
}
286 chars
18 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.

related categories

gistlibby LogSnag