If I wish to calculate if all Bool
s in the list are true
with this snippet, why won't the types be correctly inferred?
let bools = [false, true, false, true]
let result = bools.reduce(true, combine: &&)
If I wish to calculate if all Bool
s in the list are true
with this snippet, why won't the types be correctly inferred?
let bools = [false, true, false, true]
let result = bools.reduce(true, combine: &&)
I encountered the same bug a while ago (but then with ||
). If you want to use reduce
for this, the easiest solution is to write
let result = bools.reduce(true, combine: { $0 && $1 })
or
let result = bools.reduce(true) { $0 && $1 }
instead. As pointed out in the comments, you can also use
let result = !bools.contains(false)
Not only is this more readable, but it's also more efficient because it will stop at the first encounter of false
rather than iterating over the entire array (though the compiler might optimize this).