Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary operator '&=' cannot be applied to two 'Bool' operands in Swift

Tags:

swift

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?

like image 722
Addev Avatar asked May 24 '17 09:05

Addev


People also ask

What is a binary operator give example?

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.

Is == a binary operator?

Some common binary operators in computing include: Equal (==) Not equal (!=)


2 Answers

&= 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 && ...
like image 75
JeremyP Avatar answered Sep 28 '22 19:09

JeremyP


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.

like image 45
Hamish Avatar answered Sep 28 '22 21:09

Hamish