首页 > 解决方案 > 如何重用具有“关联类型”的协议中的功能?

问题描述

考虑以下情况:

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.")
    }
}

如果没有associatedtype,则表达式(self as P).f()正常。有没有一种方法可以重用P.f()when Phas associtedtype

标签: swiftswift-protocolscode-reuseswift-extensionsassociated-types

解决方案


我不认为这是可能的。但是有一个简单的解决方法:

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.")
    }
}

推荐阅读