简体   繁体   English

Swift 3协议重载运算符

[英]Swift 3 Overload Operators for Protocols

I have a protocol that declares property of type Int . 我有一个声明Int类型属性的协议 I also have few classes that conforms that Protocol , and now I need to overload operator + for all of them. 我也有一些符合该Protocol类,现在我需要为所有它们重载operator + Since operator + will work based on the property declared, I don't want to implement that operator in each class separately. 由于运算符+将基于声明的属性工作,因此我不想在每个类中单独实现该运算符。

So I have 所以我有

protocol MyProtocol {
    var property: Int { get }
}

And I would want to have something like 我想有这样的东西

extension MyProtocol {
    static func +(left: MyProtocol, right: MyProtocol) -> MyProtocol {
        // create and apply operations and return result
    }
}

And actually I successfully did that, but trying to work with it I get an error ambiguous reference to member '+' . 实际上,我成功地做到了这一点,但是尝试使用它,我得到了ambiguous reference to member '+'的错误ambiguous reference to member '+'

When I move operator overload func to the each class separately, issue disappeared, but I'm still looking for a solution to make it works with Protocols. 当我将运算符重载函数分别移至每个类时,问题消失了,但我仍在寻找一种解决方案以使其与协议兼容。

Solved, by moving func +... outside of Extension, so it is just a method in the file where MyProtocol is declared 通过将func +...移动到Extension之外来解决,因此它只是声明MyProtocol的文件中的方法

protocol MyProtocol {
    var property: Int { get }
}

func +(left: MyProtocol, right: MyProtocol) -> MyProtocol {
    // create and apply operations and return result
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM