0
0
Swiftprogramming~5 mins

Overriding methods and properties in Swift

Choose your learning style9 modes available
Introduction

Overriding lets you change how a method or property works in a child class. It helps you customize behavior without changing the original code.

You want a child class to do something different when a method runs.
You want to change the value or behavior of a property in a subclass.
You need to add extra steps before or after the original method runs.
You want to fix or improve how a method or property works in a subclass.
Syntax
Swift
class Parent {
    func greet() {
        print("Hello from Parent")
    }
}

class Child: Parent {
    override func greet() {
        print("Hello from Child")
    }
}
Use the override keyword before the method or property you want to change.
You can only override methods or properties that are not marked as final in the parent class.
Examples
The Dog class changes the sound() method to print "Bark" instead of "Some sound".
Swift
class Animal {
    func sound() {
        print("Some sound")
    }
}

class Dog: Animal {
    override func sound() {
        print("Bark")
    }
}
The Car class overrides the speed property to return a higher value.
Swift
class Vehicle {
    var speed: Int {
        return 50
    }
}

class Car: Vehicle {
    override var speed: Int {
        return 100
    }
}
The Student class calls the original method with super and adds more text.
Swift
class Person {
    func description() {
        print("I am a person")
    }
}

class Student: Person {
    override func description() {
        super.description()
        print("I am also a student")
    }
}
Sample Program

This program shows how the Cat class changes the sound() method from the Animal class.

Swift
class Animal {
    func sound() {
        print("Animal makes a sound")
    }
}

class Cat: Animal {
    override func sound() {
        print("Meow")
    }
}

let myAnimal = Animal()
myAnimal.sound()

let myCat = Cat()
myCat.sound()
OutputSuccess
Important Notes

Always use override to avoid mistakes and make your code clear.

You can call the original method or property using super if you want to keep some original behavior.

Summary

Overriding lets a subclass change methods or properties from its parent.

Use the override keyword before the method or property.

You can call the original version with super if needed.