Sequence(and in particular Collectionand Array) has a (short-circuited) contains(where:)method that takes boolean predicate as an argument. For instance,
if array.contains(where: { $0 % 2 == 0 })
checks if the array contains any even number.
There is no โallโ method, but you can use contains()as well as denying both the predicate and the result. For instance,
if !array.contains(where: { $0 % 2 != 0 })
checks if all numbers in the array are even. Of course, you can define your own extension method:
extension Sequence {
func allSatisfy(_ predicate: (Iterator.Element) -> Bool) -> Bool {
return !contains(where: { !predicate($0) } )
}
}
If you want to allow predicate throwing in the same way as
contains, then it will be defined as
extension Sequence {
func allSatisfy(_ predicate: (Iterator.Element) throws -> Bool) rethrows -> Bool {
return try !contains(where: { try !predicate($0) } )
}
}
source
share