0
0
Swiftprogramming~5 mins

Comparing structs vs classes decision in Swift

Choose your learning style9 modes available
Introduction

Structs and classes are two ways to group data and behavior in Swift. Choosing between them helps you write clear and efficient code.

When you want simple data containers that don't need inheritance.
When you want to avoid accidental changes by copying data instead of sharing it.
When you need reference sharing and inheritance features.
When you want to manage memory carefully with reference counting.
When you want to model real-world objects that have identity.
Syntax
Swift
struct MyStruct {
    var property: Int
}

class MyClass {
    var property: Int
    init(property: Int) {
        self.property = property
    }
}

Structs are value types: they are copied when assigned or passed around.

Classes are reference types: they share the same instance when assigned or passed around.

Examples
Changing p2 does not affect p1 because structs are copied.
Swift
struct Point {
    var x: Int
    var y: Int
}

var p1 = Point(x: 1, y: 2)
var p2 = p1
p2.x = 10
print(p1.x)  // prints 1
print(p2.x)  // prints 10
Changing person2 also changes person1 because classes share the same instance.
Swift
class Person {
    var name: String
    init(name: String) {
        self.name = name
    }
}

var person1 = Person(name: "Alice")
var person2 = person1
person2.name = "Bob"
print(person1.name)  // prints Bob
print(person2.name)  // prints Bob
Sample Program

This program shows how changing a struct copy does not affect the original, but changing a class copy does.

Swift
struct Car {
    var model: String
}

class Bike {
    var model: String
    init(model: String) {
        self.model = model
    }
}

var car1 = Car(model: "Sedan")
var car2 = car1
car2.model = "Coupe"

var bike1 = Bike(model: "Mountain")
var bike2 = bike1
bike2.model = "Road"

print("car1 model: \(car1.model)")
print("car2 model: \(car2.model)")
print("bike1 model: \(bike1.model)")
print("bike2 model: \(bike2.model)")
OutputSuccess
Important Notes

Use structs for simple data that should not change unexpectedly.

Use classes when you need shared state or inheritance.

Remember that structs are thread-safe by default because they are copied.

Summary

Structs are copied; classes are shared.

Choose structs for simple, independent data.

Choose classes for shared, complex objects with identity.