swift – 对成员的模糊引用\u0026\u0026 [复制]

参见英文答案 >
Use logical operator as combine closure in reduce                                    5个

如果我想用这个片段来计算列表中的所有Bool是否都是真的,为什么不能正确推断这些类型呢?

let bools = [false, true, false, true]
let result = bools.reduce(true, combine: &&)

最佳答案 我前一段时间遇到过同样的错误(但随后又出现了||).如果你想为此使用reduce,最简单的解决方案是编写

let result = bools.reduce(true, combine: { $0 && $1 })

要么

let result = bools.reduce(true) { $0 && $1 }

代替.正如评论中指出的那样,您也可以使用

let result = !bools.contains(false)

这不仅更具可读性,而且更高效,因为它会在第一次遇到false时停止,而不是遍历整个数组(尽管编译器可能会对此进行优化).

点赞