Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources
Protocol Inheritance Tutorial

Protocol Inheritance in Swift

Introduction to Protocols

In Swift, a protocol is a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. Protocols can be adopted by classes, structures, and enumerations. They provide a way to achieve polymorphism in Swift.

What is Protocol Inheritance?

Protocol inheritance allows a protocol to inherit the requirements of another protocol. This means that when a new protocol is defined, it can include all the requirements of an existing protocol, allowing for more flexible and modular code.

Defining a Protocol

To define a protocol in Swift, you use the protocol keyword followed by the protocol name. Here’s a simple example:

protocol Vehicle {

var numberOfWheels: Int { get }

func drive()

}

This protocol defines a requirement for the number of wheels and a method to drive.

Inheriting Protocols

When you define a new protocol, you can inherit from one or more existing protocols by listing them after a colon. Here’s how it works:

protocol ElectricVehicle: Vehicle {

var batteryLevel: Int { get }

func charge()

}

In this example, the ElectricVehicle protocol inherits from the Vehicle protocol, meaning it must implement both the requirements of Vehicle and its own requirements.

Conforming to Inherited Protocols

When a class adopts a protocol that inherits from another protocol, it must conform to all inherited requirements. Here's how you can implement a class that conforms to the ElectricVehicle protocol:

class Tesla: ElectricVehicle {

var numberOfWheels: Int { return 4 }

var batteryLevel: Int { return 100 }

func drive() { print("Driving") }

func charge() { print("Charging") }

}

The Tesla class successfully conforms to both the Vehicle and ElectricVehicle protocols by implementing all required properties and methods.

Multiple Protocol Inheritance

Swift allows a protocol to inherit from multiple protocols. Here’s an example:

protocol Flying {

func fly()

}

protocol Bird: Vehicle, Flying {

func layEggs()

}

The Bird protocol inherits from both the Vehicle and Flying protocols, meaning any class that adopts Bird must conform to all requirements from both protocols.

Conclusion

Protocol inheritance in Swift is a powerful feature that allows for greater flexibility and modularity in your code. By defining protocols that can inherit from other protocols, you can create a clear and organized structure that can be easily extended. Understanding protocol inheritance is crucial for mastering Swift's type system and achieving efficient code design.