Swift Array.allSatisfy() Method: Tutorial & Examples

Updated: May 5, 2023 By: Khue Post a comment

The Fundamentals

The array allSatisfy() method in Swift is a built-in way of checking whether all items in an array match a condition. You can give this method a closure that takes an element of the array as its argument and returns a Boolean value that indicates whether the passed element satisfies the condition. The method will apply that condition on all elements until it finds one that fails, at which point it will return false. If no element fails the test or the array is empty, the method will return true.

The syntax of the array allSatisfy() method in Swift is:

array.allSatisfy(condition)

Here, condition is a closure that accepts a condition and returns a Bool value.

A closure is a self-contained block of code that can be passed around and used in your code. You can think of it as a function without a name. You can use $0, $1, $2, etc. to refer to the first, second, third, etc. parameters passed into the closure. For example, the closure below checks if a number is greater than 5:

{ $0 > 5 }

And this closure checks if a string has the prefix “S”:

{ $0.hasPrefix("S") }

Now, it’s time to see some real-world examples of using the allSatisfy() method in practice.

Examples

Checking if all elements in an array are greater than a given number

The code:

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

In this example, we create an array of numbers and use the allSatisfy() method to check if all of them are greater than 5. The condition is a closure that takes a number as an argument and returns true if it is greater than 5 and false otherwise. The output is true because all the numbers in the array satisfy the condition.

Checking if all elements in an array of custom types satisfy a condition

In this example, we’ll check if all people in a group are older than 20 or not.

struct Person {
    var name: String
    var age: Int
}

var people = [
    Person(name: "The One-Arm Wolf", age: 33),
    Person(name: "Demon SLayer", age: 99),
    Person(name: "Badman", age: 35),
]

// check if all people are older than 20 or not
var result = people.allSatisfy { $0.age > 20 }

if(result) {
    print("All people are older than 20")
} else {
    print("Not all people are older than 20")
}

Output:

All people are older than 20

Conclusion

You’ve learned about the array allSastisfy() method in Swift. It’s really useful in many scenarios that you will encounter in your career. If you have any questions related to this method, feel free to leave comments. I’m more than happy to hear from you. Good luck & have a nice day!