Swift
Structure vs Class
Swift Programming
iOS Development
Swift Language

structure vs class in swift language

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Swift, Apple's powerful and intuitive programming language, uses both structures (struct) and classes (class) to encapsulate data and behavior in a single entity. While they might appear similar at first glance, they come with distinct characteristics and are used in different scenarios based on the needs of the application. This article will delve into the differences and similarities between structures and classes in Swift, providing technical insights and examples to help you choose the right construct for your needs.

Structures and Classes: Key Characteristics

Both structures and classes allow you to define properties to store values, define methods to provide functionality, and define initializers to set up their initial state. However, they have significant differences that affect how you use them in your code.

Value Types vs Reference Types

  1. Value Types: Structure
    • struct in Swift is a value type, which means each instance of a structure holds a unique copy of its data.
    • When you assign a structure or pass a structure to a function, you are actually working with a copy of the original structure.
swift
1    struct Point {
2        var x: Int
3        var y: Int
4    }
5
6    var point1 = Point(x: 10, y: 20)
7    var point2 = point1
8    point2.x = 30
9
10    print(point1.x) // Output: 10
11    print(point2.x) // Output: 30
  1. Reference Types: Class
    • class is a reference type. Multiple references can point to the same memory space.
    • When you assign a class instance or pass it to a function, you are passing a reference to the same instance.
swift
1    class Circle {
2        var radius: Double
3        init(radius: Double) {
4            self.radius = radius
5        }
6    }
7
8    let circle1 = Circle(radius: 10)
9    let circle2 = circle1
10    circle2.radius = 20
11
12    print(circle1.radius) // Output: 20
13    print(circle2.radius) // Output: 20

Inheritance

  • Structures: Do not support inheritance. You cannot create a structure that inherits the properties or behavior of another structure.
  • Classes: Support inheritance, allowing a class to inherit methods, properties, and other characteristics from another class.
swift
1    class Vehicle {
2        var speed: Double = 0.0
3    }
4
5    class Car: Vehicle {
6        var brand: String = ""
7    }

Memory Management

  • Structures: Use Automatic Reference Counting (ARC) for memory management, but since they are value types, they generally do not exhibit reference counting behavior.
  • Classes: Use ARC, which keeps track of the number of references to an object and deallocates the object when the reference count is zero.

Identity Operators

  • Structures: Do not have identity because they are value types.
  • Classes: Can be checked for identity using the === and !== operators to determine if two constants or variables refer to the same instance.
swift
1    let class1 = Circle(radius: 10)
2    let class2 = class1
3    let class3 = Circle(radius: 10)
4
5    if class1 === class2 {
6        print("class1 and class2 are the same instance")
7    } else {
8        print("class1 and class2 are different instances")
9    }
10
11    if class1 === class3 {
12        print("class1 and class3 are the same instance")
13    } else {
14        print("class1 and class3 are different instances")
15    }

Mutability

  • Structures: let and var can be used to define immutable and mutable structures. You must use mutating keyword in a method if it modifies properties of a structure.
swift
1    struct Square {
2        var side: Double
3
4        mutating func scale(by factor: Double) {
5            side *= factor
6        }
7    }
  • Classes: Properties within a class can be defined as let or var. A property defined with var can be modified regardless of whether the instance itself was declared using let or var.

Deinitializers

  • Structures: Cannot define deinitializers.
  • Classes: Can use deinit to free up resources.
swift
1    class FileHandle {
2        deinit {
3            closeFile()
4        }
5    }

Summary Table

Feature/PropertyStructureClass
TypeValueReference
InheritanceNot SupportedSupported
Memory ManagementUses ARC, no reference countUses ARC
Identity OperatorsNot Available=== and !== operators
MutabilityUse mutating for methodsProperties can be mutable
DeinitializersNot SupportedSupported using deinit

Conclusion

The choice between using a structure or a class in Swift should be guided by the specific requirements of your application. Structures are generally preferred for encapsulating simple data constructs and when inheritance is not needed. On the other hand, classes are more suitable when you need to model complex data structures that require inheritance and shared data across different instances. Understanding the distinctions between structures and classes is vital for writing efficient, maintainable, and readable Swift code.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.