Swift program to check all array elements satisfy a condition

Here, we are going to learn how to check all array elements satisfy a condition in Swift programming language?
Submitted by Nidhi, on June 17, 2021

Problem Solution:

Here, we will create an array of integer elements. Then we will check a condition for all array elements using the allSatisfy() function. The allSatisfy() function returns Boolean value based on condition.

Program/Source Code:

The source code to check all array elements satisfy a condition is given below. The given program is compiled and executed successfully.

// Swift program to check all array elements
// satisfy a condition

import Swift

var arr:[Int] = [12,10,25,20,50]

var res = arr.allSatisfy {
    $0 < 60
}

print(res)

Output:

true

...Program finished with exit code 0
Press ENTER to exit console.

Explanation:

In the above program, we imported a package Swift to use the print() function using the below statement,

import Swift;

Here, we created an array arr that contains 5 integer elements. Then we checked a condition that all array elements are less than 60 or not using allSatisfy() function and print result on the console screen.

Swift Array Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.