0
0
Swiftprogramming~5 mins

Classes are reference types in Swift

Choose your learning style9 modes available
Introduction

Classes let you create objects that share the same data by reference. This means when you change one object, others that point to it also see the change.

When you want multiple parts of your program to share and update the same data.
When you need to model real-world things that have identity and can change over time.
When you want to pass big objects around without copying all their data.
When you want to create complex data structures like linked lists or trees.
When you want to use inheritance to create new types based on existing ones.
Syntax
Swift
class ClassName {
    var property: Type
    init(property: Type) {
        self.property = property
    }
}

Classes are defined with the class keyword.

Instances of classes are reference types, so variables hold references to the same object.

Examples
This defines a simple class Person with a name property.
Swift
class Person {
    var name: String
    init(name: String) {
        self.name = name
    }
}
Both person1 and person2 refer to the same object. Changing person2.name also changes person1.name.
Swift
let person1 = Person(name: "Alice")
let person2 = person1
person2.name = "Bob"
print(person1.name)  // Output: Bob
Sample Program

This program shows that carA and carB point to the same Car object. Changing the color through carB also changes it for carA.

Swift
class Car {
    var color: String
    init(color: String) {
        self.color = color
    }
}

let carA = Car(color: "Red")
let carB = carA
carB.color = "Blue"
print("carA color: \(carA.color)")
print("carB color: \(carB.color)")
OutputSuccess
Important Notes

Unlike structs, classes are reference types, so assignment copies the reference, not the data.

Use === to check if two variables refer to the exact same class instance.

Summary

Classes create reference type objects that share the same data.

Changing one reference changes all references to that object.

Use classes when you want shared, mutable objects.