Understanding Classes and Inheritance in Swift

A portrait painting style image of a pirate holding an iPhone.

by The Captain

on
April 1, 2024

Working with Classes in Swift

Introduction: Classes are a fundamental building block in Swift programming, allowing you to define blueprints for objects with properties and methods. In this tutorial, we will explore how to work with classes in Swift, create instances of classes, and understand inheritance and initialization.

Creating a Class:

class Person {
    var name: String
    var age: Int
    
    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }
    
    func greet() {
        print("Hello, my name is \(name)!")
    }
}

In the code snippet above, we define a simple Person class with name and age properties, an initializer method to initialize these properties, and a greet() method to print a greeting message.

Creating an Instance:

let person1 = Person(name: "Alice", age: 30)
person1.greet() // Output: Hello, my name is Alice!}

We create an instance of the Person class called person1 with the name "Alice" and age 30. We then call the greet() method on the person1 instance to print the greeting message.

Inheritance:

class Student: Person {
    var studentID: Int
    
    init(name: String, age: Int, studentID: Int) {
        self.studentID = studentID
        super.init(name: name, age: age)
    }
    
    override func greet() {
        print("Hello, my name is \(name) and my student ID is \(studentID)!")
    }
}

In the code above, we create a Student class that inherits from the Person class. The Student class adds a studentID property, overrides the greet() method to include the student ID, and calls the superclass initializer using super.init().

Conclusion:

Working with classes in Swift allows for the creation of reusable and organized code structures. Understanding classes and inheritance is crucial for building complex and scalable applications in Swift.