1

Consider the following situation:

protocol P {
    associatedtype T = String
    func f()
}

extension P {
    func f() {print("I want to reuse this function")}
}

class A: P {
    func f() {
        (self as P).f() // can't compile
        print("do more things.")
    }
}

If there is no associatedtype, the expression (self as P).f() is OK. Is there a method to reuse P.f() when P has associtedtype?

蘇哲聖
  • 735
  • 9
  • 17

1 Answers1

2

I don't think it's possible. But there's a simple workaround:

protocol P {
    associatedtype T = String
    func f()
}

extension P {
    func f() {g()}
    func g() {print("I want to reuse this function")}
}

class A: P {
    func f() {
        self.g() // no problem with compilation, calls protocol's implementation
        print("do more things.")
    }
}
timbre timbre
  • 12,648
  • 10
  • 46
  • 77
  • That works only if we can modify the code of `f()` in `extension P`. – 蘇哲聖 Nov 13 '20 at 03:12
  • 2
    @蘇哲聖 No, it's sufficient to modify the code of class A. The problem here is that you're trying to get protocol-and-adopter to behave like superclass-and-subclass, which is silly. If you want to be able to call the extension's `f` just don't "override" it with another `f`. – matt Nov 13 '20 at 04:13