swift - 如何重用具有“关联类型”的协议中的功能?
问题描述
考虑以下情况:
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 P
has associtedtype
?
解决方案
我不认为这是可能的。但是有一个简单的解决方法:
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.")
}
}
推荐阅读
- mysql - 修改 JSON 对象数组中的属性
- reactjs - 由于移除了 React 中的千位分隔符,导致 onClick 时光标向右跳
- delphi - 如何使用 tadodataset delphi 从多表中读取记录并在发布时保存在表中
- mqtt - Mosquitto MQTT 设置下行
- javascript - 用户重新加载页面时打开最后一个活动选项卡
- docker - 使用 docker 在远程的 pycharm 中配置解释器
- reactjs - 当仅参数更改但更改浏览器中的 url 时,History.push 不会重定向
- office-addins - Outlook 加载项 - 检测是否在 Outlook for Mac“新外观”中运行?
- react-native - React Native expo-location:如何让后台位置服务更新更频繁?
- c# - 无法命中包含泛型类型的 API 端点