Remove All Elements From Array in Swift

In this short Swift code example, you will learn how to:

  • Initialize an Array with 5 elements in Swift
  • How to remove all elements from an Array

Initialize Array with 5 elements

In the code example below, we will create a new array with 5 elements and we will print out all this array to preview its elements.

// Initialize Array with 5 elements
var myArray = [1,2,3,4,5]
// Print Array contents to preview
print(myArray)

Remove All Elements

Now that we have an error with elements let’s learn how to empty it and remove all its elements. To do that we will use the array’s built-in function called removeAll(). Calling the removeAll() function will remove all elements from an array.

// Remove all elements from Array
myArray.removeAll()
// Print Array contents to preview
print(myArray)

For more Swift code examples and tutorials, please check the Swift Code Examples page on this website.


Leave a Reply

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