ios - 逻辑二进制中缀运算符出错

标签 ios swift operators

我想像在 Objective-C 中一样添加自定义运算符 &=:

precedencegroup HighPrecedence {
    assignment: true
    associativity: left
    higherThan: BitwiseShiftPrecedence
}

infix operator &= : HighPrecedence
func &=(lhs: Bool, rhs: @autoclosure () -> Bool) -> Bool {
    return lhs && rhs()
}

var i = true
i &= 1 > 0

但是我在最后一行有一个错误:

error: left side of mutating operator isn't mutable: 'i' is immutable i &= 1 > 0

谁能帮帮我?

最佳答案

您的&= 运算符改变 左边的操作数,因此您有 将 lhs 定义为 inout 参数(而不是返回 一个值)。

您也可以删除您的运算符定义,&= 已定义 在 Swift 标准库中作为

infix operator &= : AssignmentPrecedence

(用于BitwiseOperations)。所以这就足够了并且按预期工作:

func &=(lhs: inout Bool, rhs: @autoclosure () -> Bool) {
    lhs = lhs && rhs()
}

var i = true
i &= 1 < 0

关于ios - 逻辑二进制中缀运算符出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41181642/

相关文章:

iphone - UIWebview 创建 SVG 'on the fly'

ios xcode header 搜索路径含义

ios - 在构建我的 Cocoapod 时,有没有办法指定对另一个分支的依赖?

ios - 如何为 UITextView Swift 添加下划线/粗体/斜体能力

ruby - map(& :name) mean in Ruby? 是什么意思

python - 学校垄断作业的一部分不会输出任何内容(初学者,Python)

ios - 更改分段控制按钮的背景颜色

ios - NSDate 中超过一年的错误

ios - 我们如何在 google place IOS API 中传递类型、page_token、排序等?

javascript - Shell 风格的函数调用?