目标C语言 组合多个Bool返回值而不短路



Swift 2对Bool值使用位运算符有限制。这很好。在ObjC中,当你需要执行每个操作数时使用它是非常有用的。例如:

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

在这种情况下,使用按位&将执行每个方法。

如果我使用逻辑运算符&&,它将执行第一个操作数,如果它为false,表达式将返回false,而不执行其他两个操作数。

我想找到与&相同的优雅方式,在Swift中使用Bool。这可能吗?

你在Objective-C中做的事情并不"优雅"。太恶心了,你不该这么做。如果你想调用三个方法,只需调用那三个方法!但是形成布尔表达式时,应该使用逻辑运算符,而不是位运算符。例如:

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

没有这样的特殊运算符,但我可能会这样做:

if ![a.isBool(), b.isBool(), c.isBool()].contains(false) {

还是

let aCondition = a.isBool()
let bCondition = b.isBool()
let cCondition = c.isBool()
if aCondition && bCondition && cCondition {

但是你也可以定义你自己的运算符

你可以在你的方法调用数组上使用reduce操作来模拟相同的行为,例如

/* example setup */
struct Foo {
    let bar: Bool
    init(_ bar: Bool) { self.bar = bar }
    func isTrue() -> Bool { print("(bar) foo!"); return bar }
}
let a = Foo(false)
let b = Foo(false)
let c = Foo(true)
/* naturally all three method calls will execute to construct the boolean
   array, whereafter reduce will evaluate the combined conditional statement */ 
if [a.isTrue(), b.isTrue(), c.isTrue()].reduce(true, combine: { $0 && $1 }) {
    print("Reached this ...")
} /* false foo!
     false foo!
     true foo! */
let d = Foo(true)
let e = Foo(true)
let f = Foo(true)
if [d.isTrue(), e.isTrue(), f.isTrue()].reduce(true, combine: { $0 && $1 }) {
    print("Reached this ...")
} /* true foo!
     true foo!
     true foo!
     Reached this ... */

或例如,将方法作为可变参数提供给执行方法的函数和组合条件

func foo(calls: (() -> Bool)...) -> Bool {
    return calls.map{ $0() }.reduce(true, combine: { $0 && $1})
}
let a = Foo(false)
let b = Foo(false)
let c = Foo(true)
if foo(a.isTrue, b.isTrue, c.isTrue) {
    print("Reached this ...")
} /* false foo!
     false foo!
     true foo! */
let d = Foo(true)
let e = Foo(true)
let f = Foo(true)
if foo(d.isTrue, e.isTrue, f.isTrue) {
    print("Reached this ...")
} /* true foo!
     true foo!
     true foo!
     Reached this ... */
let values = [a.isFoo(), b.isFoo(), c.isFoo()]
let result = values.allSatisfy { $0 }

最新更新