O'Reilly logo

Mastering Swift 4 - Fourth Edition by Jon Hoffman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Removing elements from an array

There are three methods that we can use to remove one or all of the elements in an array. These methods are removeLast(), remove(at:), and removeAll(). The following example shows how to use the three methods to remove elements from the array:

var arrayOne = [1,2,3,4,5] 
arrayOne.removeLast()  //arrayOne now contains 1, 2, 3 and 4 
arrayOne.remove(at:2)  //arrayOne now contains 1, 2 and 4  
arrayOne.removeAll()  //arrayOne is now empty 

The removeLast() and remove(at:) methods will also return the value of the element being removed. Therefore, if we want to know the value of the item that was removed, we can rewrite the remove(at:) and removeLast() lines to capture the value, as shown in the following example:

var ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required