Articles and podcasts about Swift development, by John Sundell.

Genius Scan SDK

Presented by the Genius Scan SDK

This article has been archived, as it was published several years ago, so some of its information might now be outdated. For more recent articles, please visit the main article feed.

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)
        ...
    }
}
Genius Scan SDK

Swift by Sundell is brought to you by the Genius Scan SDK — Add a powerful document scanner to any mobile app, and turn scans into high-quality PDFs with one line of code. Try it today.