我试图在Bool
中累积结果进行多次检查:
我的代码是:
var validParams = login.characters.count > 4;
validParams &= password.characters.count > 6;
validParams &= ...
// more validations
if (validParams) {...}
但我收到错误Binary operator '&=' cannot be applied to two 'Bool' operands
。
如何在非详细模式下完成此工作或重写此代码?
答案 0 :(得分:3)
&=
是bitwise operation,只能应用于整数类型。由于short circuiting,您所需要的&&=
实际上并不存在。你需要写
validParams = validParams && ...
答案 1 :(得分:2)
作为@JeremyP says,&=
是in-place bitwise AND operator,它只对整数类型进行操作。但是,没有什么可以阻止您为就地逻辑AND操作定义自己的&&=
运算符:
infix operator &&= : AssignmentPrecedence
func &&=(lhs: inout Bool, rhs: @autoclosure () -> Bool) {
// although it looks like we're always evaluating rhs here, the expression "rhs()" is
// actually getting wrapped in a closure, as the rhs of && is @autoclosure.
lhs = lhs && rhs()
}
然后您可以像这样简单地使用它:
func someExpensiveFunc() -> Bool {
// ...
print("some expensive func called")
return false
}
var b = false
b &&= someExpensiveFunc() // someExpensiveFunc() not called, as (false && x) == false.
print(b) // false
b = true
b &&= someExpensiveFunc() // someExpensiveFunc() called, as (true && x) == x
print(b) // false
正如您所看到的,因为我们将rhs:
&&=
参数设为@autoclosure
参数,我们可以对lhs
为{{{{{{{ 1}}。