Object-Oriented Programming in Swift
# 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 ahealth 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
structandclass.
- 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 astruct.
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 aclass.
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*.
*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.8. Visual Learning: OOP Structure
9. Common Mistakes
-
Mutating Struct Methods: If you have a
structand 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 themutatingkeyword: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 aclassif you explicitly need shared memory (reference semantics) or Inheritance (which structs do not support).
11. Exercises
-
1.
Create a
structnamedBookwith properties fortitle(String) andauthor(String). Create an instance of this book.
-
2.
Add a method
read()to the struct that prints "Now reading [title]".
12. Coding Challenges
Challenge: Create astruct 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
In Swift, which architectural construct automatically provides a "Memberwise Initializer", saving the developer from manually writing an init() function?
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
Viewhierarchy instead of traditional UIKit Classes?
-
Q: What is the specific purpose of the
mutatingkeyword 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).