Delete all array elements in Swift

In this tutorial, we will delete all the elements of a given array in Swift. For this, we will use removeAll() function in Swift.

removeAll()

This function deletes all the elements from an array list.

The syntax for this is-

array.removeAll()

This function optionally takes a condition, if the condition is satisfied it just deletes all the elements from the array and does not return any value to the user only updates the array.

Implementation

This function works to remove all the elements from an array. We will first initialize an integer array and try to print before and after invoking the function removeAll().

Snippet to delete all the elements from an array-

var arr=[1,4,5,6,4]
print(arr)
arr.removeAll()
print(arr)
Output-[1, 4, 5, 6, 4]
[]

The removeAll() function is invoked and as we can see all the elements from the array are removed.

If you want to delete all the elements from an array only if a certain condition is satisfied, then you can put it within the bracket and if it returns true then all the elements are deleted.

So we have accomplished the task to delete all the elements from an array. Thanks for reading! I hope you enjoyed reading it!

Leave a Reply

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