Structs vs Classes

Structs and classes are similar in that they both allow you to define custom data types in Swift. However, there are some important differences between structs and classes that you should be aware of.

The main difference between structs and classes is that structs are value types, whereas classes are reference types. This means that when you assign a struct to a new variable or constant, you are creating a new copy of the struct, and the new variable or constant is independent of the original struct. However, when you assign a class to a new variable or constant, you are not creating a new instance of the class, but instead creating a reference to the existing instance.

Here's a simple example that illustrates the difference between structs and classes in Swift:

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

class Person {
    var name: String
    var age: Int
}

var point1 = Point(x: 1.0, y: 2.0)
var point2 = point1
point2.x = 3.0

var john = Person(name: "John", age: 30)
var jane = john
jane.name = "Jane"

In this example, the Point struct and the Person class are defined with two properties each. Then, two variables are declared for each type: point1 and point2 for the Point struct, and john and jane for the Person class.

When the point2 variable is assigned the value of the point1 variable, a new copy of the Point struct is created, and the point2 variable is independent of the point1 variable. This is shown when the x coordinate of the point2 variable is modified, and the x coordinate of the point1 variable remains unchanged.

However, when the jane variable is assigned the value of the john variable, a new reference to the existing Person instance is created, and the jane variable is not independent of the john variable. This is shown when the name property of the jane variable is modified, and the name property of the john variable is also modified as a result.

In addition to the value vs. reference type difference, there are a few other important differences between structs and classes in Swift.

Previous
Previous

What does having “Scalable Code“ mean?

Next
Next

Understanding Classes