Protocol extensions with default implementations
📖 Scenario: Imagine you are building a simple app that manages different types of vehicles. Each vehicle can describe itself with a message. You want to make it easy to add new vehicle types without rewriting common code.
🎯 Goal: You will create a protocol called Vehicle with a method to describe the vehicle. Then, you will add a protocol extension that provides a default description. Finally, you will create specific vehicle types that use the default description or provide their own.
📋 What You'll Learn
Create a protocol named
Vehicle with a method func description() -> StringAdd a protocol extension for
Vehicle that provides a default implementation of description()Create a struct
Car that conforms to Vehicle and uses the default descriptionCreate a struct
Bicycle that conforms to Vehicle and provides its own description() implementationPrint the descriptions of both
Car and Bicycle instances💡 Why This Matters
🌍 Real World
Protocol extensions with default implementations let you write flexible and reusable code. For example, apps that manage many types of objects can share common behavior easily.
💼 Career
Understanding protocol extensions is important for Swift developers. It helps in writing clean, maintainable code and is widely used in iOS app development.
Progress0 / 4 steps