0
0
Swiftprogramming~5 mins

Base class and subclass in Swift

Choose your learning style9 modes available
Introduction

Base classes let you create a general blueprint. Subclasses let you make special versions that add or change things.

When you want to share common features between different objects.
When you want to create a general type and then make more specific types from it.
When you want to reuse code and avoid repeating yourself.
When you want to organize your code in a clear, logical way.
When you want to add new features to an existing class without changing it.
Syntax
Swift
class BaseClass {
    // properties and methods
}

class SubClass: BaseClass {
    // extra properties and methods
}

Use a colon : to show that one class is a subclass of another.

The subclass gets all the properties and methods of the base class automatically.

Examples
Here, Dog is a subclass of Animal. It can do everything Animal can, plus bark.
Swift
class Animal {
    func sound() {
        print("Some sound")
    }
}

class Dog: Animal {
    func bark() {
        print("Woof!")
    }
}
Bicycle changes the number of wheels and the drive behavior from the base Vehicle class.
Swift
class Vehicle {
    var wheels = 4
    func drive() {
        print("Driving")
    }
}

class Bicycle: Vehicle {
    override var wheels: Int {
        get { 2 }
        set { }
    }
    override func drive() {
        print("Pedaling the bicycle")
    }
}
Sample Program

This program shows a base class Person and a subclass Student. The subclass adds a new property and changes the greeting.

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

class Student: Person {
    var school: String
    init(name: String, school: String) {
        self.school = school
        super.init(name: name)
    }
    override func greet() {
        print("Hi, I'm \(name) and I study at \(school)")
    }
}

let person = Person(name: "Alice")
person.greet()

let student = Student(name: "Bob", school: "Greenwood High")
student.greet()
OutputSuccess
Important Notes

Use override keyword when a subclass changes a method or property from the base class.

Call super.init() in subclass initializers to set up the base class part.

Subclasses inherit all non-private properties and methods from the base class.

Summary

Base classes provide a general template.

Subclasses extend or change the base class features.

Use inheritance to reuse code and organize related classes.