DEV Community

Naveen Ragul B
Naveen Ragul B

Posted on • Edited on

Swift - Inheritance

  • Inheritance  is a mechanism in which one object (base Class) acquires all the properties and behaviors of a parent object(sub Class).

  • Methods, Properties, and Subscripts can be inherited and can be overrided by subclass if needed.

example :

class Vehicle {
    var currentSpeed = 0.0
    var description: String {
        return "traveling at \(currentSpeed) miles per hour"
    }
    func makeNoise() {
        //make a noise
    }
}
Enter fullscreen mode Exit fullscreen mode
class Bicycle: Vehicle {
    var hasBasket = false
}

bicycle.currentSpeed = 15.0
print("Bicycle: \(bicycle.description)")
Enter fullscreen mode Exit fullscreen mode

Overriding

  • Custom implementation can be provided by subclass for an instance method, type method, instance property, type property, or subscript if needed using override keyword.. This is known as overriding.
  • While overriding a method, property, or subscript, existing superclass implementation can be included as part of your override using super keyword.

example :

class Train: Vehicle {
    override func makeNoise() {
        print("Choo Choo")
    }
}
let train = Train()
train.makeNoise()
Enter fullscreen mode Exit fullscreen mode
  • Any custom Getters and Setters can be overrided, regardless of whether the inherited property is implemented as a stored or computed property at source. Both the name and the type of the property should be provided by overriding class.

  • Inherited read-only property can be overrrided as a read-write property. But inherited read-write property can't be overrrided as a read-only property.

  • To override a setter property, you must also provide a getter for that override. If you don’t want to modify the inherited property’s value within the overriding getter, you can simply pass through the inherited value by returning super.someProperty from the getter.

  • You can’t add property observers to inherited constant stored properties or inherited read-only computed properties. The value of these properties can’t be set, and so it isn’t appropriate to provide a willSet or didSet.

  • Both an overriding setter and an overriding property observer can’t be provided for the same property. If you want to observe changes to a property’s value, and you are already providing a custom setter for that property.

Preventing Overrides

  1. To prevent a method, property, or subscript from being overridden use final keyword.
  2. To prevent any attempt to subclass a class, use final keyword before the class.

Top comments (0)