在reduce中使用逻辑运算符作为联合闭包 [英] Use logical operator as combine closure in reduce

查看:181
本文介绍了在reduce中使用逻辑运算符作为联合闭包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过应用逻辑运算符 OR || )减少 Bool code>)使用下面的代码,但是我得到一个错误:

  func reduceBools(values:[Bool]) - > Bool {
return values.reduce(false,combine:||)
}



< blockquote>

对成员||的模糊引用


类似地,整数类似于charm。

  func reduceInts(values:[Int]) - > Int {
return values.reduce(0,combined:+)
}

我可以通过添加一个 || 函数(下面的代码)或使用 {$ 0 || $ 1} 闭包,但我不喜欢这些方法,我宁愿简单地传递运算符。

  func | |(1hs:Bool,rhs:Bool) - > Bool {
return lhs ||对于逻辑 AND ,同样的事情发生在逻辑 AND && )运算符。



如何在不使用上述hack


$ b

$ p <$ p <$ p <$ p <$ p> > // ||
func reduceBoolsOr(values:[Bool]) - > Bool {
return values.contains(true)
}

//&&
func reduceBoolsAnd(values:[Bool]) - >请注意,Bool {
return!values.contains(false)
}



.reduce 附带开销。如果最终结果是您的问题的重要性(而不是查询 || & 运算符),那么上面的实用方法可能是有帮助的,即使它不真正减少数组,但是由于布尔的简单性质产生相同的结果类型。


I am trying to reduce an array of Bools by applying the logical operator OR (||) using the following code, however I get an error:

func reduceBools(values: [Bool]) -> Bool {
    return values.reduce(false, combine: ||)
}

Ambiguous reference to member '||'

Analogously for integers the code works like a charm.

func reduceInts(values: [Int]) -> Int {
    return values.reduce(0, combine: +)
}

I was able to make it work by adding a || function (code below) or using a { $0 || $1 } closure but I dislike these approaches and I would prefer simply passing the operator.

func ||(lhs: Bool, rhs: Bool) -> Bool {
    return lhs || rhs
}

The same thing happens for the logical AND (&&) operator.

How can I make it work without using the hack above?

解决方案

As an alternative, you could use the following approach

// ||
func reduceBoolsOr(values: [Bool]) -> Bool {
    return values.contains(true)
}

// &&
func reduceBoolsAnd(values: [Bool]) -> Bool {
    return !values.contains(false)
}

Note that .reduce comes with an overhead. If the end result is the importance of your question (rather than enquiring above the unexpected behaviour of || and && operators in this context), then perhaps the pragmatic approach above can be of help, even if it doesn't really reduce the array, however producing the same result due to the simple nature of the boolean type.

这篇关于在reduce中使用逻辑运算符作为联合闭包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆