【问题标题】:Swift 3 Overload Operators for ProtocolsSwift 3 协议重载运算符
【发布时间】:2018-04-14 18:07:45
【问题描述】:

我有一个声明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 '+'

当我将运算符重载函数分别移动到每个类时,问题就消失了,但我仍在寻找一种解决方案,使其适用于协议。

【问题讨论】:

    标签: ios swift xcode operator-overloading


    【解决方案1】:

    解决了,通过将func +...移到Extension之外,所以它只是MyProtocol被声明的文件中的一个方法

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

    【讨论】:

      猜你喜欢
      • 2017-03-10
      • 2016-04-06
      • 1970-01-01
      • 1970-01-01
      • 2021-07-05
      • 1970-01-01
      • 1970-01-01
      • 2015-12-23
      • 2017-06-05
      相关资源
      最近更新 更多