Weekly Swift articles, podcasts and tips by John Sundell.

The ‘final’ keyword

Published on 19 Mar 2019

Swift's final keyword is not only useful in order to prevent a class from being subclassed entirely, it can also let us mark individual methods as non-overridable — which is useful when relying on subclassing, and we still want to protect certain methods from being modified:

// A class that isn't 'final' can be subclassed within its own
// module (outside of the module, only if it's marked as 'open').
class Actor {
    func willMove(to scene: Scene) {
        ...
    }

    func didMove(to scene: Scene) {
        ...
    }

    // However, individual functions can still be marked as
    // 'final' to prevent overrides.
    final func remove() {
        ...
    }
}

extension Actor {
    // Methods defined in extensions can't be overriden either,
    // at least not yet.
    func add(to scene: Scene) {
        ...
    }
}

class Player: Actor {
    // This is especially useful when setting up a hierarchy
    // of classes that derive from a parent class, and we only
    // want to enable specific overrides.
    override func willMove(to scene: Scene) {
        super.willMove(to: scene)
        ...
    }
}