Search code examples
objective-cswiftbitwise-and

Combining multiple Bool return values without shortcircuiting


Swift 2 has restrictions on using bitwise operators for Bool values. This is agreeable. In ObjC it was very useful to use it when you need to execute each operand. For example:

a.isFoo() & b.isFoo() & c.isFoo()

In this case, using the bitwise & will execute each method.

If I use the logical operator &&, it will execute the first one and if it is false, the expression will return false without executing the other two operands.

I want to find the same elegant way that & works, with Bool in Swift. Is it possible?


Solution

  • What you were doing in Objective-C was not "elegant". It was skanky and you shouldn't have been doing it. If you want to call three methods, just call those three methods! But forming a boolean expression, you should use the logical operators, not the bitwise operators. So, for example:

    let (ok1, ok2, ok3) = (a.isBool(), b.isBool(), c.isBool())
    let ok = ok1 && ok2 && ok3