Preventing inheritance
Sometimes you’ll want to disallow subclasses of a particular class. Swift provides the final keyword for you to guarantee a class will never get a subclass:
final class Student: Person {
//…
}
// Build error!
class StudentAthlete: Student {
//…
}
By marking the Student class final, you tell the compiler to prevent any classes from inheriting from Student. This can remind you — or others on your team! — that a class wasn’t designed to have subclasses.
Additionally, you can mark individual methods as final, if you want to allow a class to have subclasses, but protect individual methods from being overridden:
class Student: Person {
final func recordGrade(_ grade: Grade) {
//…
}
}
class StudentAthlete: Student {
// Build error!
override func recordGrade(_ grade: Grade) {
//…
}
}
There are benefits to initially marking any new class you write as final. Not only does it tell the compiler it doesn’t need to look for any more subclasses, which can shorten compile time, it also requires you to be very explicit when deciding to subclass a class previously marked final. You will learn more about controlling who can override a class in Chapter 19, “Access Control and Code Organization”.