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

I am trying to do a few checks, accumulating the result in Bool:

My code is:

 var validParams = login.characters.count > 4;
 validParams &= password.characters.count > 6;
 validParams &= ...
 // more validations
 if (validParams) {...}

But I get an error message Binary operator '&=' cannot be applied to two 'Bool' operands.

How can I do this work or rewrite this code in mode without verification?

+4
source share
2 answers

&=is a bitwise operation and can only be applied to integer types. &&=that you need does not actually exist due to a short circuit . You need to write

validParams = validParams && ...
+2
source

@JeremyP , &= - AND, . , &&= 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: &&= a @autoclosure, , lhs - false.

+2

Source: https://habr.com/ru/post/1677833/


All Articles