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 arrayOne = [1,2,3,4,5] 
var removed1 = arrayOne.removeLast() //removed1 contains the value 5  
var removed = arrayOne.remove(at: 2)//removed contains the value 3 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset