Swift Program to Remove All the Elements from the Array


This tutorial will discuss how to write swift program to get the magnitude of the number.

An array is an ordered collection which is used to store same type of data. For example, if any array is of integer type then it will only store integers, you are strictly not allowed to store elements of other data types like string, float, etc.

To remove all the elements from the specified array Swift provide an in-built library function named removeAll(). The removeAll() function will delete all the items from the specified array. Or it can delete elements that match the given condition.

Below is a demonstration of the same −

Syntax

Following is the syntax −

arrayName.removeAll(where:)

Here, where is the condition. When the condition is satisfied, then the elements are removed. It is optional.

Algorithm

Following is the algorithm −

  • Step 1 − Create an array with values.

  • Step 2 − Remove all the elements using removeAll() function −

arrNumbers.removeAll()
  • Step 3 − Print the output

Remove all the elements from the array

Example

The following program shows how to remove all the elements from the array.

import Foundation import Glibc // Creating an array of integer type var arrNumbers = [44, 100, 10, 19, 29, 200, 300, 34] print("Original Array:", arrNumbers) // Remove all the elements from the array arrNumbers.removeAll() print("Modified Array:", arrNumbers)

Output

Original Array: [44, 100, 10, 19, 29, 200, 300, 34]
Modified Array: []

Here, in the above code, we have an array of integer type named arrNumbers. Now we remove all the elements of arrNumbers using removeAll() function −

arrNumbers.removeAll()

Hence the resultant array is empty.

Remove all the elements that match the condition

Example 

The following program shows how to remove all the elements from the array that matches the given condition.

import Foundation import Glibc // Creating an array of string type var arrNames = ["Tom", "Pinky", "Owl", "Pompom", "XOXO", "Jerry", "Mom"] print("Original Array:", arrNames) // Remove all the elements from the array // Whose length is less than 4 arrNames.removeAll(where: {$0.count < 4}) print("Modified Array:", arrNames)

Output

Original Array: ["Tom", "Pinky", "Owl", "Pompom", "XOXO", "Jerry", "Mom"]
Modified Array: ["Pinky", "Pompom", "XOXO", “Jerry"]

Here, in the above code, we have an array named arrNames of string type. Now we remove all the elements whose size is less than 4. So to this we passed this condition in the removeAll() function −

arrNames.removeAll(where: {$0.count < 4})

Here $0 represents the first element whose length is less than 4. So the removed elements are: [“Tom”, “Owl”, “Mom”]. Therefore the resultant array is ["Pinky", "Pompom", "XOXO", “Jerry”].

Updated on: 20-Oct-2022

505 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements