4

If I wish to calculate if all Bools 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: &&)
matt
  • 515,959
  • 87
  • 875
  • 1,141
Skyler
  • 2,834
  • 5
  • 22
  • 34
  • I suggest you look [here](http://stackoverflow.com/a/34699637/5654848). It is explained in detail. – Mtoklitz113 Jul 02 '16 at 16:22
  • 1
    You can simply write this as `let result = !bools.contains(false)`, which will compile with ambiguity btw :) But definitely interested in exactly why this is ambiguous. – Hamish Jul 02 '16 at 16:23

1 Answers1

1

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).

Tim Vermeulen
  • 12,352
  • 9
  • 44
  • 63