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

var numbers = [6, 7, 8, 9]

// check if all elements are greater than 5 or not var result = numbers.allSatisfy({ $0 > 5})
print(result) // Output: true

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

var languages = ["Swedish", "Spanish", "Serbian"]

// check if all elements start with "S" or not var result = languages.allSatisfy( { $0.hasPrefix("S") } )
print(result)

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

var numbers = [2, 4, 6, 7, 8]

// check if all elements are even numbers or not var result = numbers.allSatisfy({ $0 % 2 == 0 })
print(result)

Output

false