0
0
Swiftprogramming~5 mins

Why classes exist alongside structs in Swift

Choose your learning style9 modes available
Introduction

Classes and structs both help organize data and behavior, but classes exist because they offer features structs don't, like shared references and inheritance.

When you want multiple parts of your program to share and change the same data easily.
When you need to create a blueprint that other blueprints can build upon (inheritance).
When you want to manage complex data that needs identity, not just value.
When you want to use features like deinitializers to clean up resources.
When you want to use reference counting to manage memory automatically.
Syntax
Swift
class ClassName {
    // properties and methods
}

struct StructName {
    // properties and methods
}

Classes are reference types, meaning variables point to the same instance.

Structs are value types, meaning variables hold their own copy.

Examples
This shows a simple class and struct both holding a name.
Swift
class Dog {
    var name: String
    init(name: String) {
        self.name = name
    }
}

struct Cat {
    var name: String
}
This example shows how changing a class instance affects all references, but changing a struct copy does not affect the original.
Swift
let dog1 = Dog(name: "Buddy")
var dog2 = dog1

dog2.name = "Max"
print(dog1.name)  // Prints "Max" because dog1 and dog2 refer to the same object

var cat1 = Cat(name: "Whiskers")
var cat2 = cat1

cat2.name = "Snowball"
print(cat1.name)  // Prints "Whiskers" because cat1 and cat2 are separate copies
Sample Program

This program shows how classes share the same instance, so changing person2 changes person1's name. Structs copy values, so changing point2 does not affect point1.

Swift
class Person {
    var name: String
    init(name: String) {
        self.name = name
    }
}

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

let person1 = Person(name: "Alice")
var person2 = person1
person2.name = "Bob"

var point1 = Point(x: 0, y: 0)
var point2 = point1
point2.x = 10

print("person1.name: \(person1.name)")
print("person2.name: \(person2.name)")
print("point1.x: \(point1.x)")
print("point2.x: \(point2.x)")
OutputSuccess
Important Notes

Use classes when you need shared, mutable state or inheritance.

Use structs for simple data that should be copied, like coordinates or settings.

Understanding the difference helps avoid bugs with unexpected data changes.

Summary

Classes and structs both organize data but behave differently.

Classes are reference types, structs are value types.

Classes exist to support shared data, inheritance, and identity.