NEW: Master Swift design patterns with my latest book! >>

< Previous: Overriding methods   Next: Copying objects >

Final classes

Although class inheritance is very useful – and in fact large parts of Apple’s platforms require you to use it – sometimes you want to disallow other developers from building their own class based on yours.

Swift gives us a final keyword just for this purpose: when you declare a class as being final, no other class can inherit from it. This means they can’t override your methods in order to change your behavior – they need to use your class the way it was written.

To make a class final just put the final keyword before it, like this:

final class Dog {
    var name: String
    var breed: String

    init(name: String, breed: String) { = name
        self.breed = breed

Master iOS 11 now!

My book Practical iOS 11 gives you seven complete coding projects that teach all the major new features in iOS 11 in a smart, practical way.

< Previous: Overriding methods   Next: Copying objects >
Click here to visit the Hacking with Swift store >>