I'm trying to make multiple checks accumulating the result in a Bool
:
My code is:
var validParams = login.characters.count > 4;
validParams &= password.characters.count > 6;
validParams &= ...
// more validations
if (validParams) {...}
But I get the error Binary operator '&=' cannot be applied to two 'Bool' operands
.
How can I do this work or rewrite this code in a non-verbose mode?
Typical examples of binary operations are the addition ( ) and multiplication ( ) of numbers and matrices as well as composition of functions on a single set. For instance, On the set of real numbers , is a binary operation since the sum of two real numbers is a real number.
Some common binary operators in computing include: Equal (==) Not equal (!=)
&=
is a bitwise operation and can only be applied to integer types. &&=
which is what you need doesn't actually exist because of short circuiting. You need to write
validParams = validParams && ...
As @JeremyP says, &=
is the in-place bitwise AND operator, which only operates on integer types. However, there's nothing to stop you from defining your own &&=
operator for an in-place logical AND operation:
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()
}
You can then simply use it like so:
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
As you can see, because we made the rhs:
parameter of &&=
an @autoclosure
parameter, we can have short-circuit evalutation for when the lhs
is false
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With