override a getter on a subclass in swift

In Swift, you can override a getter in a subclass by providing your own implementation of the computed property using the override keyword. Here's an example:

main.swift
class Parent {
    var value: Int {
        get {
            return 10
        }
    }
}

class Child: Parent {
    override var value: Int {
        get {
            return super.value + 5
        }
    }
}
210 chars
16 lines

In the example above, we have a Parent class with a computed property value that returns the value 10. We create a Child class that inherits from Parent and overrides the value property to return a value equal to the parent's value plus 5.

To override a getter in a subclass in Swift, you need to:

  1. Declare the computed property in the subclass with the same name and type as in the superclass.
  2. Prefix it with the override keyword.
  3. Provide your own implementation of the getter.
  4. Optionally call the superclass implementation using super. followed by the property name to access its implementation.

gistlibby LogSnag