0
0
Swiftprogramming~5 mins

Calling super for parent behavior in Swift

Choose your learning style9 modes available
Introduction
Sometimes, you want a child class to do its own work and also keep the work the parent class does. Calling super lets you run the parent's code too.
When you want to add extra steps to a method but keep the original behavior.
When overriding a method but still need the parent class to do its setup.
When customizing a function but not losing the parent's important actions.
Syntax
Swift
override func methodName() {
    super.methodName()
    // your extra code here
}
Use 'super' to call the parent class's version of the method.
Call to 'super' can be before or after your extra code depending on what you want.
Examples
Child calls the parent's greet first, then adds its own message.
Swift
class Parent {
    func greet() {
        print("Hello from Parent")
    }
}

class Child: Parent {
    override func greet() {
        super.greet()
        print("And hello from Child")
    }
}
Child runs some code, then parent's setup, then more code.
Swift
class Parent {
    func setup() {
        print("Parent setup")
    }
}

class Child: Parent {
    override func setup() {
        print("Child setup start")
        super.setup()
        print("Child setup end")
    }
}
Sample Program
Car's start method adds checks, then calls Vehicle's start, then confirms start.
Swift
class Vehicle {
    func start() {
        print("Vehicle is starting")
    }
}

class Car: Vehicle {
    override func start() {
        print("Car checks before starting")
        super.start()
        print("Car has started")
    }
}

let myCar = Car()
myCar.start()
OutputSuccess
Important Notes
If you forget to call super when needed, the parent behavior won't run.
In some cases, calling super is required by the language or framework.
You can call super multiple times, but usually once is enough.
Summary
Use 'super' to run the parent class's method inside an override.
This helps keep original behavior and add new steps.
Order of calling super matters for the final result.