Swift class inheritance with override, super, final and two-phase init.
In one line
Building a new class (the child) on top of an existing one (the parent), keeping its properties and methods and changing only what you need with override. In Swift only classes inherit.
Why you need it
Write walks, runs and hill runs as unrelated types and the title, minutes and summary code appears three times. Changing the summary means three edits.
Keep the shared part in Workout once, and give each child only what differs (distance, climb) and its own calculation. Change the summary once in the parent and every workout follows.
Everyday picture
Think of a basic recipe and its variations. Kimchi fried rice inherits the basic fried rice recipe and rewrites one step, "fry the kimchi first", following the rest as written. The last variation may carry a note saying "no more changes" (final).
Example code
main.swift · 57 lines
let walk = Workout(title: "Walk", minutes: 40)let run = Run(minutes: 30, km: 6)let hill = HillRun(minutes: 30, km: 5, climb: 150)for w in [walk, run, hill] {print(w.report())}classWorkout {let title: Stringlet minutes: Intinit(title: String, minutes: Int) {self.title = titleself.minutes = minutes }funccalories() -> Int {let kcal = minutes * 4return kcal }funcreport() -> String {"\(title) \(minutes) min, \(calories()) kcal" }}classRun: Workout {let km: Intinit(title: String = "Run", minutes: Int, km: Int) {self.km = kmsuper.init(title: title, minutes: minutes) }overridefunccalories() -> Int {let kcal = km * 60return kcal }overridefuncreport() -> String {super.report() + ", \(km) km" }}finalclassHillRun: Run {let climb: Intinit(minutes: Int, km: Int, climb: Int) {self.climb = climbsuper.init(title: "Hill run", minutes: minutes, km: km) }overridefunccalories() -> Int {let extra = climb / 2returnsuper.calories() + extra }}
Swift code does not run on this page. Save your edited code as main.swift on your own computer, compile it with swiftc and run it.
When to use it
Classes fit the sentence "X is a kind of Y" (a run is a kind of workout)
You reuse almost all of the parent and change one or two things (override plus super)
Close classes that must not be extended with final; the compiler can also make calls faster.
Structs and enums have no inheritance. To make several types do the same job, use the protocols in the next topics.
An init reaches its parent with super.init(...); a method reaches the parent version with super.method().
Common mistakes
Calling super.init first
The order is the opposite of Java. In Swift the child must set all of its own properties before calling the parent init, so the child is never half-empty even if the parent calls an overridden method.
When the parent already has a method with that name, you must write override. The compiler stops you from replacing parent behavior by accident. Writing override on a method the parent does not have is also an error.
Wrong
let yoga = Yoga(title: "Yoga", minutes: 30)print(yoga.report())classYoga: Workout {funccalories() -> Int { minutes * 3 }}
What the Swift compiler sayserror: overriding declaration requires an 'override' keyword
Fixed
let yoga = Yoga(title: "Yoga", minutes: 30)print(yoga.report())classYoga: Workout {overridefunccalories() -> Int { minutes * 3 }}
When you run itYoga 30 min, 90 kcal
Inheriting from a final class
final class means the line ends here. Put it on classes whose rules would break if extended. If you must inherit, branch off a parent that is not final (Run). A child with no new properties inherits the parent initializers as they are.
Wrong
classTrailRun: HillRun {}
What the Swift compiler sayserror: inheritance from a final class 'HillRun'
Fixed
print(TrailRun(minutes: 10, km: 2).report())classTrailRun: Run {}
When you run itRun 10 min, 120 kcal, 2 km
Check yourself
Question 1
The variable type is Workout, but the object is a Run. What is printed?
let w: Workout = Run(minutes: 10, km: 2)print(w.calories())
Show the answer
Answer: 2. 120 An overridden method is chosen by the real object, not the variable type: the Run rule gives 2 × 60 = 120.
Question 2
Can a struct inherit from a class?
structStretch: Workout {}
Show the answer
Answer: 2. A compile error Only classes inherit. Structs and enums can list only protocols after the colon, so naming a class is a compile error.
Questions people ask
Can a struct inherit?
No. Only classes inherit. To share behavior among structs and enums, use protocols and extensions.
When does a child init call super.init?
After the child has set every property it added, the opposite order to Java. Once the parent init returns, you may change inherited properties and call methods.
Why mark something final?
To close classes and methods whose rules would break if subclassed or overridden. Since nothing can override them, the compiler can also choose faster calls.