ios - 是否可以在 Swift 中重载 += 运算符?

标签 ios swift operator-overloading operators overloading

是否可以在 Swift 中重载 += 运算符以接受例如 CGFloat 参数?如果是,怎么办?

我的方法(如下)不起作用。

infix operator += { associativity left precedence 140 }
public func +=(inout left: CGFloat, right: CGFloat) {
    left = left + right
}

(编辑)重要:

上面的编码方法确实有效。请see my answer below解释为什么我认为没有。

最佳答案

对不起,我的错。运算符 += 不需要为 CGFloat 参数重载,因为这样的重载包含在 Swift 中。我正在尝试做类似的事情

let a: CGFloat = 1.5
a += CGFloat(2.1)

这失败了,因为我无法分配给 let 并且 XCode 显示的错误让我很困惑。

当然,像我原来的问题(下面)中那样的方法适用于重载运算符。

infix operator += { associativity left precedence 140 }
public func +=(inout left: CGFloat, right: CGFloat) {
    left = left + right
}

请随意投票以结束此问题。

关于ios - 是否可以在 Swift 中重载 += 运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26746951/

相关文章:

android - Android 的 stretchableImageWithLeftCapWidth (iOS) 是什么?

swift - 我收到此错误 "Attempt to set a non-property-list object as an NSUserDefaults"

swift - 使用 DispatchQueue swift 3 下载图像时发现 Optional 为 nil

c++ - "Essential C++": Providing Class Instances of the iostream Operators

operator-overloading - Ada Compiler 放弃通过重载运算符的包的实例化

ios - Cordova 应用程序视频无法在 iOS10 上播放 - 401 错误

ios - 内容类型 JSON SIGABRT 错误

c# - 嵌套隐式运算符

ios - 通过向左/向右滑动来最小化对象,同时将另一个对象最大化到屏幕上

swift - 应用程序仍处于开发模式...Facebook - 测试用户无法选择使用电子邮件登录