Filter array elements in swift based on if condition

This tutorial will see how to filter array elements based on the if condition in Swift. Arrays are data structures that store the data but are of the same data type. They are of fixed size.

Algorithm

Step 1: Declare an array of some data type (e.g.-Integer, String) and assign the array elements. Now declare another empty array of the same data type to store the filtered elements.

Step 2: Now use the loop to iterate through the array (e.g.-While Loop, For loop). Inside the loop specify the if condition to filter the array elements. If the condition satisfies then append that element to the empty array defined previously.

  • in: It is the keyword in Swift which is used to get values from some collection.
  • append(element): It is a function that adds the specified element at the end of the collection.

Step 3: Print the filtered array based on the if condition.

Code

Here is the code snippet to filter array elements in Swift.

var numbers:[Int] = [1,57,44,23,89,65,41,22,30,10,70,2,0]
var filtered = [Int]()
for i in numbers 
{
    if i > 50
    {
        filtered.append(i)   
    }    
}
print(filtered)

Output:

[57, 89, 65, 70]

Also, refer to Remove duplicate elements from an array in Swift

Leave a Reply

Your email address will not be published. Required fields are marked *