Search code examples
swiftabstractswift-protocols

Swift - class method which must be overridden by subclass


Is there a standard way to make a "pure virtual function" in Swift, ie. one that must be overridden by every subclass, and which, if it is not, causes a compile time error?


Solution

  • You have two options:

    1. Use a Protocol

    Define the superclass as a Protocol instead of a Class

    Pro: Compile time check for if each "subclass" (not an actual subclass) implements the required method(s)

    Con: The "superclass" (protocol) cannot implement methods or properties

    2. Assert in the super version of the method

    Example:

    class SuperClass {
        func someFunc() {
            fatalError("Must Override")
        }
    }
    
    class Subclass : SuperClass {
        override func someFunc() {
        }
    }
    

    Pro: Can implement methods and properties in superclass

    Con: No compile time check