The super Keyword
super is how a subclass reaches back up to its parent class to use the parent's own version of something.
Syntax
class Subclass: Superclass {
var newProperty: Type
init(newProperty: Type, inherited: Type) {
self.newProperty = newProperty
super.init(inherited: inherited)
}
override func method() { super.method() }
}
Calling super.init in a Subclass Initializer
When a subclass adds its own properties, its initializer typically sets those first, then calls super.init(...) to let the superclass initialize its own properties.
Example: Calling super.init in a Subclass Initializer
// Define a class `Vehicle`
class Vehicle {
var wheels: Int
init(wheels: Int) {
self.wheels = wheels
}
}
// Define a class `Car`
class Car: Vehicle {
var brand: String
init(brand: String) {
self.brand = brand
super.init(wheels: 4)
}
}
// Declare a constant `car`, set to `Car(brand: "Ford")`
let car = Car(brand: "Ford")
// Print "\(car.brand) has \(car.wheels) wheels" to the console
print("\(car.brand) has \(car.wheels) wheels")
Login to try C/C++/Java/PHP code in the editor
Using super in an Overridden Method
super.methodName() inside an override calls the superclass's original implementation of that method.
Example: Using super in an Overridden Method
// Define a class `Greeter`
class Greeter {
// Define the function `greet` with no parameters and returning a String
func greet() -> String {
// Return `"Hello"` from this function
return "Hello"
}
}
// Define a class `EnthusiasticGreeter`
class EnthusiasticGreeter: Greeter {
override func greet() -> String {
// Return `super.greet() + "!!!"` from this function
return super.greet() + "!!!"
}
}
// Print `EnthusiasticGreeter().greet()` to the console
print(EnthusiasticGreeter().greet())
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Forgetting to call
super.init(...)in a subclass's custom initializer when the superclass has its own required setup. - Using
superoutside of a class (e.g. in a struct), where it has no meaning since structs don't support inheritance. - Calling
super.method()at the wrong point in an override, when the parent behavior was meant to run before or after new logic, not instead of it.
Chapter Summary
superrefers to the current class's immediate superclass.super.init(...)calls the superclass's initializer, often required to set up inherited properties.super.method()invokes the superclass's version of an overridden method.supercan only be used within a subclass, never in a class with no superclass.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: