Swift - Copying The Behavior Of Arrays And Dictionaries

Introduction

You can copy an array by assigning it to another variable or constant, like this:

var array1 = [1,2,3,4,5]
var array2 = array1

In the preceding example, array1 is assigned to another variable array2.

In Swift, when you assign an array to another variable, a copy of the original array is duplicated and assigned to the second array

To prove this, you can make some changes to array1 and then output the content of both arrays:

var array1 = [1,2,3,4,5]
var array2 = array1

array1 [1] = 20
print(array1)  //[1,20,3,4,5]
print(array2)  //[1,2,3,4,5]

A change to array1 's element only affects itself.

For dictionaries, a copy of the dictionary is created and assigned to the second variable.

Consider the following example dictionary:

var colors =  [
   1 : "Red",
   2 : "Green",
   3 : "Blue"
]

The following statement copies the dictionary to another one:

var copyOfColors = colors

Make a change to the colors dictionary

colors [1] = "Yellow"

and print the values for both dictionaries:

var colors =  [
   1 : "Red",
   2 : "Green",
   3 : "Blue"
]

var copyOfColors = colors
colors [1] = "Yellow"

for color in colors {
   print(color)
}

for color in copyOfColors {
   print(color)
}

Related Topic