Sta*_*nov 0 xcode operator-overloading ios swift
我有一个声明 type 属性的协议Int。我也有几个符合该要求的类Protocol,现在我需要+为所有这些类重载运算符。由于运算符+将根据声明的属性工作,因此我不想在每个类中单独实现该运算符。
所以我有
protocol MyProtocol {
var property: Int { get }
}
Run Code Online (Sandbox Code Playgroud)
我想要有类似的东西
extension MyProtocol {
static func +(left: MyProtocol, right: MyProtocol) -> MyProtocol {
// create and apply operations and return result
}
}
Run Code Online (Sandbox Code Playgroud)
实际上我成功地做到了这一点,但尝试使用它时出现错误ambiguous reference to member '+'。
当我将运算符重载函数分别移动到每个类时,问题消失了,但我仍在寻找一种解决方案以使其与协议一起使用。
解决了,通过移动到func +...扩展之外,所以它只是MyProtocol声明的文件中的一个方法
protocol MyProtocol {
var property: Int { get }
}
func +(left: MyProtocol, right: MyProtocol) -> MyProtocol {
// create and apply operations and return result
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
977 次 |
| 最近记录: |