Skip to main content
Swift for iOS Development
CHAPTER 07 Beginner

Object-Oriented Programming in Swift

Updated: May 16, 2026
6 min read

# CHAPTER 7

Object-Oriented Programming in Swift

1. Introduction

In a video game, an enemy isn't just a single string or integer. An enemy has a health integer, a name string, and an attack() function. Programming these distinct pieces separately is chaotic. Object-Oriented Programming (OOP) solves this by bundling data (Properties) and behaviors (Methods) together into a single, logical blueprint called a Class or a Struct. In this chapter, we will master OOP in Swift. We will build architectural blueprints, spawn instances (Objects) from them, and uncover the critical, interview-defining difference between Classes and Structs.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Define custom data models using struct and class.
  • Add variables (Properties) and functions (Methods) to your models.
  • Instantiate Objects from your blueprints.
  • Understand the difference between Value Types (Structs) and Reference Types (Classes).
  • Build a basic architectural model for an application.

3. What is a Blueprint?

Think of a car factory. The engineers draw a blueprint of a car. The blueprint itself cannot be driven. But the factory uses that blueprint to build 10,000 physical cars.
  • The Blueprint is the Class / Struct.
  • The physical cars are the Objects (Instances).

4. Structs (The Swift Standard)

In Swift, the most common way to build a blueprint is using a struct.
swift
12345678910111213141516171819
// 1. Defining the Blueprint
struct Player {
    // Properties (Data)
    var name: String
    var health: Int
    
    // Methods (Behaviors inside the struct)
    func takeDamage(amount: Int) {
        print("\(name) took \(amount) damage!")
    }
}

// 2. Creating the Object (Spawning the physical car!)
var playerOne = Player(name: "Arthur", health: 100)
var playerTwo = Player(name: "John", health: 80)

// 3. Accessing the Object using 'Dot Notation'
print(playerOne.name) // Prints "Arthur"
playerOne.takeDamage(amount: 20)

Notice how Swift automatically created an initializer Player(name:health:) for us! This is called a *Memberwise Initializer*, and it is a massive benefit of Structs.

5. Classes (The Legacy System)

You can build the exact same blueprint using a class.
swift
123456789101112
class Enemy {
    var name: String
    var health: Int
    
    // Classes DO NOT get automatic initializers. You MUST write it manually!
    init(name: String, health: Int) {
        self.name = name
        self.health = health
    }
}

var boss = Enemy(name: "Bowser", health: 500)

6. The Big Interview Question: Structs vs Classes

If they look so similar, why do we have both? Because of how they behave in memory!
  • Structs are VALUE Types: If you copy a struct, Swift creates a physically separate clone. Modifying the clone does NOT affect the original.
  • Classes are REFERENCE Types: If you copy a class, you are just creating a new pointer to the exact same object in memory. Modifying the copy *mutates the original*.
swift
1234567891011
// STRUCT BEHAVIOR (Clones)
var a = Player(name: "A", health: 100)
var b = a  // CLONES 'a'
b.name = "B"
print(a.name) // Prints "A". The original is safe!

// CLASS BEHAVIOR (Shared Memory)
var x = Enemy(name: "X", health: 100)
var y = x  // Points to the SAME EXACT ENEMY!
y.name = "Y"
print(x.name) // Prints "Y". The original was mutated!

*Apple highly recommends using Structs for almost everything in SwiftUI, as immutability prevents massive bugs!*

7. Mini Project: Student Management Model

Let's model a school system using OOP.
swift
123456789101112131415161718
struct Student {
    let id: String
    var name: String
    var grade: Double
    
    // A method to evaluate the student
    func isPassing() -> Bool {
        return grade >= 60.0
    }
}

// Spawning the objects
let student1 = Student(id: "001", name: "Alice", grade: 85.5)
let student2 = Student(id: "002", name: "Bob", grade: 45.0)

// Utilizing the methods
print("\(student1.name) passing? \(student1.isPassing())") // true
print("\(student2.name) passing? \(student2.isPassing())") // false

8. Visual Learning: OOP Structure

txt
123456789
[ BLUEPRINT: struct Car ]
    |-- Properties (Color, TopSpeed)
    |-- Methods (Drive(), Brake())

        | (Instantiating)
        v
[ OBJECT 1 ]                 [ OBJECT 2 ]
color: Red                   color: Blue
TopSpeed: 150                TopSpeed: 90

9. Common Mistakes

  • Mutating Struct Methods: If you have a struct and you write a method that tries to change one of its own properties (e.g., self.health -= 10), the compiler will error! Because structs are value types (immutable by default), you must explicitly mark the method with the mutating keyword: mutating func takeDamage().

10. Best Practices

  • Default to Structs: In Objective-C, everything was a Class. In modern Swift, you should always start by creating a struct. Only upgrade it to a class if you explicitly need shared memory (reference semantics) or Inheritance (which structs do not support).

11. Exercises

  1. 1. Create a struct named Book with properties for title (String) and author (String). Create an instance of this book.
  1. 2. Add a method read() to the struct that prints "Now reading [title]".

12. Coding Challenges

Challenge: Create a struct named BankAccount. Give it a property balance: Double. Write a mutating func named deposit that accepts an amount and adds it to the balance. Spawn an account and test the deposit method.

13. MCQ Quiz with Answers

Question 1

In Swift, which architectural construct automatically provides a "Memberwise Initializer", saving the developer from manually writing an init() function?

Question 2

You assign an existing Class object to a new variable (var newEnemy = oldEnemy), and then change the name of newEnemy. What happens to oldEnemy?

14. Interview Questions

  • Q: Explain the mechanical difference between a Value Type and a Reference Type in Swift memory architecture.
  • Q: Why did Apple architect SwiftUI to rely almost entirely on Structs for its UI View hierarchy instead of traditional UIKit Classes?
  • Q: What is the specific purpose of the mutating keyword when writing a function inside a Swift Struct?

15. FAQs

Q: Can a Struct inherit properties from another Struct? A: No! Inheritance (e.g., class Dog: Animal) is strictly a feature of Classes. If you want to share behaviors between Structs in Swift, you use Protocols (which act like interfaces/contracts).

16. Summary

In Chapter 7, we graduated to enterprise architecture via Object-Oriented Programming. We encapsulated raw data and logic into cohesive blueprints. We learned that Structs are the modern Swift standard, acting as fast, safe, immutable Value Types with automatic initializers. We contrasted them with legacy Classes, understanding the shared-memory dangers of Reference Types. By mastering "Dot Notation", we seamlessly instantiated and manipulated complex Objects.

17. Next Chapter Recommendation

Our Objects are brilliant, but right now we only have two of them. What if we have a school with 10,000 Student objects? We need a way to group them. Proceed to Chapter 8: Swift Collections: Arrays, Dictionaries, and Sets.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·