如果我希望使用此代码段计算列表中的所有Bool
是否为true
,为什么不能正确推断这些类型?
let bools = [false, true, false, true]
let result = bools.reduce(true, combine: &&)
答案 0 :(得分:1)
我前一段时间遇到过同样的错误(但后来遇到||
)。如果您想使用reduce
,最简单的解决方案是编写
let result = bools.reduce(true, combine: { $0 && $1 })
或
let result = bools.reduce(true) { $0 && $1 }
代替。正如评论中指出的那样,您也可以使用
let result = !bools.contains(false)
这不仅更具可读性,而且效率更高,因为它会在第一次遇到false
时停止,而不是遍历整个数组(尽管编译器可能会对此进行优化)。