Structs vs Classes in Swift

Structs vs Classes in Swift


Structs and classes are two key constructs in Swift that allow developers to define custom data types. While they may seem similar in functionality, they differ fundamentally in behavior, memory management, and use cases.


Key Differences Between Structs and Classes

1. Type:

Struct: Structs are value types, which means they are copied when assigned to a new variable or passed to a function.

Class: Classes are reference types, which means multiple variables can refer to the same instance.

Example for Structs:


struct Point {

    var x: Int

    var y: Int

}


var p1 = Point(x: 0, y: 0)

var p2 = p1  // p2 is a copy of p1

p2.x = 10

print(p1.x)  // Output: 0

print(p2.x)  // Output: 10


Example for Classes:


class Point {

    var x: Int

    var y: Int


    init(x: Int, y: Int) {

        self.x = x

        self.y = y

    }

}


let p1 = Point(x: 0, y: 0)

let p2 = p1  // p2 refers to the same instance as p1

p2.x = 10

print(p1.x)  // Output: 10

print(p2.x)  // Output: 10


2. Inheritance:

Struct: Structs do not support inheritance. They can conform to protocols to achieve some level of extensibility.

Class: Classes support inheritance, allowing you to create hierarchies where a class can inherit methods and properties from another class.

Example:


class Vehicle {

    func move() {

        print("Vehicle is moving")

    }

}


class Car: Vehicle {

    override func move() {

        print("Car is moving")

    }

}


let car = Car()

car.move()  // Output: Car is moving


3. Mutability:

Struct: Structs require the use of the mutating keyword in methods that modify their properties. This ensures immutability unless explicitly stated.

Class: Classes allow modification of properties freely without any additional keywords.

Example with Structs:


struct Counter {

    var value: Int


    mutating func increment() {

        value += 1

    }

}


var counter = Counter(value: 0)

counter.increment()

print(counter.value)  // Output: 1


Example with Classes:


class Counter {

    var value: Int = 0


    func increment() {

        value += 1

    }

}


let counter = Counter()

counter.increment()

print(counter.value)  // Output: 1


4. Memory Management:

Struct: Structs are stored on the stack. They are lightweight and efficient for small data types.

Class: Classes are stored on the heap and managed using Automatic Reference Counting (ARC). This makes them suitable for large and complex objects but can introduce overhead.


5. Identity:

Struct: Structs do not have identity. Two structs with the same data are considered equal.

Class: Classes have identity. Two class instances with the same data are not considered equal unless they refer to the same instance.

Example for Structs:


struct Point {

    var x: Int

    var y: Int

}


let p1 = Point(x: 1, y: 1)

let p2 = Point(x: 1, y: 1)

print(p1 == p2)  // Output: true


Example for Classes:


class Point {

    var x: Int

    var y: Int


    init(x: Int, y: Int) {

        self.x = x

        self.y = y

    }

}


let p1 = Point(x: 1, y: 1)

let p2 = Point(x: 1, y: 1)

print(p1 === p2)  // Output: false


6. Use Cases:

Struct:

Best for lightweight models where copying is desired, such as PointSize, or Rectangle.

Ideal for thread-safe operations because each instance is independent.

Class:

Best for complex data models requiring shared references or inheritance, such as UserDatabaseManager, or ViewController.


When to Use Structs vs Classes


Use Structs When:

The data is simple and immutable.

Copying behavior is desired when passing to functions or assigning to variables.

You don’t need reference semantics or inheritance.


Use Classes When:

You need reference semantics to share state between different parts of your program.

You require inheritance to create hierarchies.

You need identity to distinguish instances even if their data matches.


Performance Considerations

1. Structs:

Faster for smaller, immutable data types because they are stored on the stack.

Each copy of a struct is independent, so no ARC overhead is involved.

2. Classes:

More memory-intensive due to heap allocation and reference counting.

Suitable for large, complex data structures or objects that need to share state.


Comments

Popular posts from this blog

Complete iOS Developer Guide - Swift 5 by @hiren_syl |  You Must Have To Know 😎 

Debugging

Swift Fundamentals You Can’t Miss! A List by @hiren_syl