Sitemap
Sara Ortiz Drada

Sara Ortiz Drada

iOS On-device ML Engineer.

Value Types vs. Reference Types in Swift

2 min readMay 19, 2024

--

Press enter or click to view image in full size

In Swift, data types are categorized into two main groups: value types and reference types.

Value Types

In Swift, structures (struct) and enumerations (enum) are value types. Here's what that means:

  • Unique: When you create an instance of a value type (like a struct or enum), Swift gives you a unique copy of the data.
  • Independent: Each instance has its own separate data. Changes to one instance do not affect other instances.

Think of it like making a photocopy of a document. If you write on one photocopy, the other photocopy remains unchanged because they are independent copies.

Example of a Value Type

struct Point {
var x: Double
var y: Double
}

var point1 = Point(x: 0.0, y: 0.0)
var point2 = point1 // point2 is a copy of point1
point2.x = 5.0

print(point1.x) // Output: 0.0 (point1 is unchanged)
print(point2.x) // Output: 5.0 (point2 is changed)

In this example:

  • point2 is a copy of point1.
  • Changing point2 does not affect point1.

Get Sara Ortiz Drada’s stories in your inbox

Join Medium for free to get updates from this writer.

Reference Types

In Swift, classes (class) are reference types. Here's what that means:

  • Shared Data: When you create an instance of a reference type, you get a reference (or pointer) to the original data.
  • Shared Instances: Changes to one reference affect all references to the same instance.

Think of it like having multiple pointers to the same document. If you change the document, all pointers see the same changes because they reference the same document.

Example of a Reference Type

class Point {
var x: Double
var y: Double

init(x: Double, y: Double) {
self.x = x
self.y = y
}
}

var point1 = Point(x: 0.0, y: 0.0)
var point2 = point1 // point2 references the same Point instance as point1
point2.x = 5.0

print(point1.x) // Output: 5.0 (point1 is also changed)
print(point2.x) // Output: 5.0 (point2 is changed)

In this example:

  • point2 is a reference to point1.
  • Changing point2 affects point1 because they reference the same instance.

Summary

  • Value Types (struct and enum): Creating a new instance makes a unique copy. Changes to one instance do not affect others.
  • Reference Types (class): Creating a new instance shares the same data. Changes to one instance affect all references to that instance.

Understanding this distinction helps you know when and why to use mutating functions. Since value types create independent copies, you need the mutating keyword to explicitly indicate when a method will modify the instance's data.

--

--