我有一个协议,它声明Int类型的属性。我也有几个符合这个Protocol的类,现在我需要为它们重载操作符+。由于运算符+将基于声明的属性工作,因此我不希望在每个类中分别实现该运算符。
所以我有
protocol MyProtocol {
var property: Int { get }
}我想要的是
extension MyProtocol {
static func +(left: MyProtocol, right: MyProtocol) -> MyProtocol {
// create and apply operations and return result
}
}实际上,我成功地做到了这一点,但是尝试使用它时,我得到了一个错误ambiguous reference to member '+'。
当我将操作符重载功能分别转移到每个类时,问题就消失了,但我仍然在寻找一个解决方案,以使它与协议一起工作。
发布于 2017-06-09 16:06:11
通过将func +...移出扩展名解决了问题,因此它只是声明MyProtocol的文件中的一个方法。
protocol MyProtocol {
var property: Int { get }
}
func +(left: MyProtocol, right: MyProtocol) -> MyProtocol {
// create and apply operations and return result
}https://stackoverflow.com/questions/44462037
复制相似问题