Josh Homann Josh Homann - 1 month ago 10
Swift Question

Why can I use operators + - * / | and & as parameters to reduce but not the binary operators || &&

Why is it that the boolean operators don't work with reduce the way that the numeric operators and bitwise operators do:

//These all run
print([1,2,4].reduce(0, +))
print([1,2,4].reduce(0, -))
print([1,2,4].reduce(1, *))
print([1,2,4].reduce(16, /))
print([1,2,4].reduce(0, &))
print([1,2,4].reduce(0, |))

//error
print([true, false, true].reduce(true, &&))
print([true, false, true].reduce(false, ||))


The last two give the message: error: cannot convert value of type '(Bool, @autoclosure () throws -> Bool) throws -> Bool' to expected argument type '(Any, Bool) throws -> Any'

Answer

This isn't the exact same question, so I won't flag it, but here's a good explanation: What is the type of the logical operators?

Also read: Use logical operator as combine closure in reduce

Comments