override a setter on a subclass in swift

To override a setter in a subclass in Swift, you can use the override keyword before the set method and call the superclass version using super.

Here is an example:

main.swift
class Superclass {
    var property: String = ""

    func setProperty(_ newValue: String) {
        property = newValue
    }
}

class Subclass: Superclass {
    override var property: String {
        get {
            return super.property
        }
        set {
            super.setProperty(newValue)
        }
    }
}
325 chars
19 lines

In this example, the Subclass inherits the property variable from its Superclass. However, it overrides its setter in order to call the superclass's setProperty method whenever the property value is set. Note that you need to use super.property to access the superclass's version of the property variable.

gistlibby LogSnag