Unexpected Behaviour of allSatisfy(_:)

I was playing around with the allSatisfy(_:) method on Sequence and found some unexpected behaviour.

I tried to see what would happen if I used it on an empty array.

var arr = [String]()

print(arr.allSatisfy { $0 is Int })
// Prints "true"

It seems to me that it would make more sense if this returns false if the sequence is empty because there are no elements to satisfy the given predicate.

Is it worthwhile to add a guard statement to the declaration of allSatisfy(_:) in the Standard Library? What do you think should be returned in this case?

1 Like

true is what I would expect as the result. All elements of the (empty) sequence satisfy the predicate (a “vacuous truth”).

6 Likes

The current behavior is the logical one.

One way to see why: we would expect that

a.allSatisfy(predicate) && b.allSatisfy(predicate)

…if and only if…

(a + b).allSatisfy(predicate)

What if b is empty?

10 Likes
Terms of Service

Privacy Policy

Cookie Policy