Swift Array allSatisfy()

The allSatisfy() method returns true if all the elements from the array satisfy the given condition. If not, it returns false.

Example


allSatisfy() Syntax

The syntax of the allSatisfy() method is:

array.allSatisfy(condition)

Here, array is an object of the Array class.


allSatisfy() Parameters

The allSatisfy() method can take one parameter:

  • condition - a closure that accepts a condition and returns a Bool value.

allSatisfy() Return Value

The allSatisfy() method returns

  • true - if all the elements satisfy the given condition
  • false - if any one of the elements doesn't satisfy the given condition

Example 1: Swift Array allSatisfy()

Output

true

In the above program, notice the closure definition,

{ $0.hasPrefix("S") }

This is a short-hand closure that checks whether all the elements in the array have the prefix "S" or not.

$0 is the shortcut to mean the first parameter passed into the closure.

The closure returns a Bool value depending upon the condition. Since each element in the languages array starts with "S", the method returns true.


Example 2: Check If All Elements Are Even Numbers Or Not

Output

false