0
0
Swiftprogramming~5 mins

Why inheritance is class-only in Swift

Choose your learning style9 modes available
Introduction

Inheritance lets one thing copy and extend another. In Swift, only classes can do this because they work with shared, changeable data.

When you want one object to reuse and add to another object's behavior.
When you need to create a family of related objects with shared features.
When you want to change or extend how an object works without rewriting it.
When you want to use polymorphism to treat different objects the same way.
When you want to manage shared, changeable data safely.
Syntax
Swift
class ParentClass {
    // properties and methods
}

class ChildClass: ParentClass {
    // extra properties and methods
}

Only class types can inherit from another class.

Structures and enums cannot use inheritance in Swift.

Examples
A Dog class inherits from Animal and changes the sound() method.
Swift
class Animal {
    func sound() {
        print("Some sound")
    }
}

class Dog: Animal {
    override func sound() {
        print("Bark")
    }
}
Structures cannot inherit from other structures.
Swift
struct Point {
    var x: Int
    var y: Int
}

// This is not allowed:
// struct ColoredPoint: Point {
//     var color: String
// }
Sample Program

This program shows a Car class inheriting from Vehicle and changing the description.

Swift
class Vehicle {
    func description() {
        print("I am a vehicle")
    }
}

class Car: Vehicle {
    override func description() {
        print("I am a car")
    }
}

let myCar = Car()
myCar.description()
OutputSuccess
Important Notes

Classes use references, so inheritance works with shared, changeable data.

Structs and enums are value types and copy data, so inheritance doesn't fit their design.

Swift uses protocols to share behavior for structs and enums instead of inheritance.

Summary

Inheritance is only for classes because they share and change data by reference.

Structs and enums use copying, so they don't support inheritance.

Use protocols to share behavior with structs and enums.