Swift OOP

Swift Object-Oriented Programming (OOP)

Object-Oriented Programming (OOP) is a programming paradigm based on the concept of "objects".

These objects can contain data in the form of properties, and code in the form of methods.

Swift is a multi-paradigm language, meaning it fully supports OOP while also embracing protocol-oriented and functional patterns.

Let's explore the core building blocks of OOP in Swift: Classes and Objects.


Classes in Swift

A class is essentially a blueprint for creating objects.

It defines the properties (variables) and methods (functions) that the objects created from it will possess.

You define a class using the class keyword.

Defining a Class:

class Car {
    var brand: String = "Unknown"
    var year: Int = 2020
    func startEngine() {
        print("The \\(brand) engine is starting...")
    }
}

Notice how the class acts as a template. It doesn't represent a specific car yet, just the concept of a car.


Creating Objects (Instances)

Once a class is defined, you can create individual instances of that class.

These instances are called objects.

You create an object by putting parentheses after the class name, like Car().

Creating an Object:

class Car {
    var brand: String = "Toyota"
}

// Creating an instance of Car let myCar = Car()

// Accessing properties using dot syntax print(myCar.brand)


Modifying Object Properties

Because objects created from classes are reference types (which we will cover later), you can modify their variable properties even if the object is assigned to a constant let.

Modifying Properties:

class Player {
    var score = 0
}

let playerOne = Player() playerOne.score = 100 // This is perfectly fine!

print("Player One Score: \(playerOne.score)")


Classes vs Structs

Swift also has Structures (struct), which look very similar to classes.

The main difference is that classes support Inheritance and are passed by Reference, while structs do not support inheritance and are passed by Value.

We will dive much deeper into these differences in upcoming chapters!


Exercise

Which keyword is used to define a blueprint for objects in Swift?