Swift - Structures as Value Types

Introduction

A structure is a value type.

When you assign a variable/constant of a value type to another variable/constant, its value is copied over.

Consider the following example:

Demo

enum StoneColor:String {
     case Black = "Black"
     case White = "White"
}

struct Chess {/*  w ww  .  java2 s  .co m*/
    var row:Int              //0...7
    var column:Int           //0...7
    var color:StoneColor
}


var stone1 = Chess (row:2, column:6, color:StoneColor.Black)
var stone2 = stone1

print("Stone1")
print(stone1.row)

print(stone1.column)
print(stone1.color.rawValue)
print("Stone2")
print(stone2.row)

print(stone2.column)
print(stone2.color.rawValue)

Result

Here, stone1 is assigned to stone2.

Therefore, stone2 will now have the same value as stone1.

This is evident by the values that are output by the preceding code snippet:

To prove that stone2 's value is independent of stone1 's, modify the value of stone1 as follows:


stone1.row = 6
stone1.column = 7
stone1.color = StoneColor.White

Then print out the values for both stones again:

Demo

enum StoneColor:String {
     case Black = "Black"
     case White = "White"
}

struct Chess {//  w  ww .j  a  v  a  2 s  . c om
    var row:Int              //0...7
    var column:Int           //0...7
    var color:StoneColor
}


var stone1 = Chess (row:2, column:6, color:StoneColor.Black)
var stone2 = stone1

print("Stone1")
print(stone1.row)

print(stone1.column)
print(stone1.color.rawValue)
print("Stone2")
print(stone2.row)

print(stone2.column)
print(stone2.color.rawValue)

stone1.row = 6
stone1.column = 7
stone1.color = StoneColor.White


print("Stone1")
print(stone1.row)
print(stone1.column)
print(stone1.color.rawValue)
print("Stone2")
print(stone2.row)
print(stone2.column)
print(stone2.color.rawValue)

Result

The values of the two stones are independent of each other.

In Swift, String, Array, and Dictionary types are implemented using structures.

As such, when they are assigned to another variable, their values are always copied.

Related Topic