Protocol default implementations and class inheritance

Unluckily this is a dangerous language limitation, of which there is an ongoing discussion on how to solve it.

My personal workaround to this that I used in the past is:

protocol Protocol: AnyObject {
    func protocolFunction()
}

extension Protocol {
    func protocolFunction() {
        _default_protocolFunction()
    }
    func _default_protocolFunction() {
        print("default function")
    }
}

class Class: Protocol {
    func classFunction() {
        protocolFunction()
    }
    func protocolFunction() {
        _default_protocolFunction()
    }
}

class Subclass: Class {
    override func protocolFunction() {
        print("subclass function")
    }
}

Ugly, I know, but to dynamically resolve protocolFunction then Class must implement it (currently).

1 Like