Swift - Classes as Reference Types

Introduction

Unlike structures, classes are reference types.

When an instance of a class is assigned to another variable or constant, a reference is made to the original instance instead of creating a new copy.

To see what this means, assume you have the following Point class:

class Point {
    var x: Double
    var y: Double
    let width: Int

    init() {
        x = 0.0
        y = 0.0
        width = 2
    }
}

The following code creates an instance pt1 of the Point and assigns it to another variable pt2:

var pt1 = Point()
pt1.x = 25.0
pt1.y = 50.0
var pt2 = pt1

Both variables are pointing to the same instance of Point. When you print out the properties of each instance:


print("pt1")
print(pt1.x)
print(pt1.y)
print("pt2")
print(pt1.x)                                                 
print(pt1.y)

Make some changes to pt1 and print out the properties of both variables again:

pt1.x = 35
pt1.y = 76

print("After modifications")
print("pt1")
print(pt1.x)
print(pt1.y)

print("pt2")
print(pt1.x)
print(pt1.y)

You will now see that the values for both instances' properties have changed, proving that both variables are indeed pointing to the same instance:

Demo

class Point {
    var x: Double
    var y: Double
    let width: Int

    init() {/* w w  w.  ja va  2s  .com*/
        x = 0.0
        y = 0.0
        width = 2
    }
}

var pt1 = Point()
pt1.x = 25.0
pt1.y = 50.0
var pt2 = pt1

print("pt1")
print(pt1.x)
print(pt1.y)
print("pt2")
print(pt1.x)                                                 
print(pt1.y)


pt1.x = 35
pt1.y = 76

print("After modifications")
print("pt1")
print(pt1.x)
print(pt1.y)

print("pt2")
print(pt1.x)
print(pt1.y)

Result

Related Topic