Making bulk changes to an array

We can use the subscript syntax with a range operator to change the values of multiple elements. The following example shows how to do this:

var arrayOne = [1,2,3,4,5] 
arrayOne[1...2] = [12,13]//arrayOne contains 1,12,13,4 and 5 

In the preceding code, the elements at indices 1 and 2 will be changed to numbers 12 and 13; therefore, arrayOne will contain 1, 12, 13, 4, and 5.

The number of elements that you are changing in the range operator does not need to match the number of values that you are passing in. Swift makes bulk changes by first removing the elements defined by the range operator and then inserting the new values. The following example demonstrates this concept:

var arrayOne = [1,2,3,4,5]  
arrayOne[1...3] = [12,13] //arrayOne now contains 1, 12, 13 and 5 

In the preceding code, the arrayOne array starts with five elements. We then replace the range of elements 1 to 3 inclusively. This causes elements 1 through 3 (three elements) to be removed from the array first. After those three elements are removed, then the two new elements (12 and 13) are added to the array, starting at index 1. After this is complete, arrayOne will contain these four elements: 1, 12, 13, and 5. Using the same logic we can also add more elements then we remove. The following example illustrates this:

var arrayOne = [1,2,3,4,5]  
arrayOne[1...3] = [12,13,14,15] 
//arrayOne now contains 1, 12, 13, 14, 15 and 5 (six elements) 

In the preceding code, arrayOne starts with five elements. We then say that we want to replace the range of elements 1 through 3 inclusively. As in the previous example, this causes elements 1 to 3 (three elements) to be removed from the array. We then add four elements (12, 13, 14, and 15) to the array, starting at index 1. After this is complete, arrayOne will contain these six elements: 1, 12, 13, 14, 15, and 5.

..................Content has been hidden....................

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