【问题标题】:how to overload an assignment operator in swift如何快速重载赋值运算符
【发布时间】:2015-07-09 22:41:51
【问题描述】:

我想覆盖 CGFloat 的“=”运算符,如下所示:

func = (inout left: CGFloat, right: Float) {
    left=CGFloat(right)
}

所以我可以做到以下几点:

var A:CGFloat=1
var B:Float=2
A=B

这可以做到吗?我收到错误Explicitly discard the result of the closure by assigning to '_'

【问题讨论】:

标签: ios swift operator-overloading


【解决方案1】:

这是不可能的 - 正如documentation 中所述:

不能重载默认赋值运算符 (=)。只有复合赋值运算符可以重载。同样,三元条件运算符 (a ? b : c) 也不能重载。

如果这不能说服您,只需将运算符更改为+=

func +=(left: inout CGFloat, right: Float) {
    left += CGFloat(right)
}

您会注意到您将不再收到编译错误。

产生误导性错误消息的原因可能是因为编译器将您的重载尝试解释为赋值

【讨论】:

    【解决方案2】:

    您不能覆盖分配,但您可以在您的情况下使用不同的运算符。例如&= 运算符。

    func &= (inout left: CGFloat, right: Float) {
        left = CGFloat(right)
    }
    

    因此您可以执行以下操作:

    var A: CGFLoat = 1
    var B: Float = 2
    A &= B
    

    顺便说一句,运营商&+&-&* 存在于 swift 中。它们代表没有溢出的 C 样式操作。 More

    【讨论】:

      【解决方案3】:

      这不是operator loading 方法。但结果可能是你所期待的

      // Conform to `ExpressibleByIntegerLiteral` and implement it
      extension String: ExpressibleByIntegerLiteral {
          public init(integerLiteral value: Int) {
              // String has an initializer that takes an Int, we can use that to
              // create a string
              self = String(value)
          }
      }
      
      extension Int: ExpressibleByStringLiteral {
          public init(stringLiteral value: String) {
              self = Int(value) ?? 0
          }
      }
      
      // No error, s2 is the string "4"
      let s1: Int = "1"
      let s2: String = 2
      
      print(s1)
      print(s2)
      print(s1 + 2)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-30
        • 2013-02-14
        • 2016-08-30
        • 1970-01-01
        相关资源
        最近更新 更多