— Swift, Array, Functional Programming — 1 min read
When working with arrays, there are times when you may want to check if all elements in the array match a particular condition. This can be achieved using the allSatisfy(_:)
method in Swift. In this article, we will explore the allSatisfy()
method and demonstrate how it can be used.
allSatisfy(_:)
is a high-order method defined on Sequence
protocol in Swift. It iterates over all elements in the sequence and returns a Boolean value indicating whether all elements satisfy a given predicate. The method takes a single argument, which is a closure that specifies the condition that all elements must satisfy.
Here's the syntax for allSatisfy(_:)
:
1func allSatisfy(_ predicate: (Element) -> Bool) -> Bool
The predicate
parameter is a closure that takes an Element
of the sequence and returns a Bool
. The Element
type is the type of the elements in the sequence.
Let's consider an example where we have an array of integers and we want to check if all elements in the array are even. We can achieve this using the allSatisfy(_:)
method as shown below:
1let numbers = [2, 4, 6, 8, 10]2let allEven = numbers.allSatisfy { $0 % 2 == 0 }3print(allEven) // true
In the code above, we first define an array of integers numbers
. We then call the allSatisfy(_:)
method on the numbers
array and pass in a closure that checks if each element in the array is even. The print()
statement outputs the result, which is true
since all elements in the array are even.
Here's another example of checking every character of a String to see if all of the individual characters are uppercase or not:
1let str = "HELLOWORLD"2let allUpper = str.allSatisfy { $0.isUppercase }3print(allUpper) // Output: true
Keep in kind that if you add a space between hello and world in the above example the output/result will be false instead.
The allSatisfy(_:)
method is a useful method in Swift for checking if all elements in a sequence match a particular condition. It is a great way to write concise and expressive code when dealing with arrays. I hope this article has been helpful in demonstrating how to use the allSatisfy(_:)
method.