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.
override func methodName() { super.methodName() // your extra code here }
class Parent { func greet() { print("Hello from Parent") } } class Child: Parent { override func greet() { super.greet() print("And hello from Child") } }
class Parent { func setup() { print("Parent setup") } } class Child: Parent { override func setup() { print("Child setup start") super.setup() print("Child setup end") } }
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()
super.methodName() inside an overridden method in Swift do?supersuper.methodName() runs the original method from the parent class, preserving its behavior.display() inside an overridden method in Swift?super followed by dot and method name to call parent methods.super.display() matches Swift syntax. Others are invalid or from other languages.class Parent {
func greet() {
print("Hello from Parent")
}
}
class Child: Parent {
override func greet() {
print("Child starts")
super.greet()
print("Child ends")
}
}
let c = Child()
c.greet()c.greet() is called?greet() method in Child prints "Child starts", then calls super.greet() which prints "Hello from Parent", then prints "Child ends".class Parent {
func show() {
print("Parent show")
}
}
class Child: Parent {
override func show() {
print("Child show")
show() // Line X
}
}Child.show(), calling show() calls itself again, causing infinite recursion.super.show() to call the parent class's method and avoid recursion.Grandparent has a method log(), Parent overrides it and calls super.log(), and Child overrides it too. You want Child.log() to add its own message, then call Parent.log(), which calls Grandparent.log(). How should you write Child.log() to achieve this?super.log() in Child calls Parent.log(), which calls Grandparent.log().super.log().Pass the test and this pattern moves unknown