Protocol extensions for shared behavior
📖 Scenario: You are building a simple app that manages different types of vehicles. Each vehicle can describe itself with a message. You want to share common behavior among all vehicles without repeating code.
🎯 Goal: Create a protocol called Vehicle with a property and a method. Then use a protocol extension to provide a shared default implementation for the method. Finally, create two structs that conform to the protocol and use the shared behavior.
📋 What You'll Learn
Create a protocol named
Vehicle with a var name: String { get } property and a func description() -> String method.Add a protocol extension for
Vehicle that provides a default implementation of description() returning a string using the name property.Create a struct called
Car that conforms to Vehicle and has a name property.Create a struct called
Bicycle that conforms to Vehicle and has a name property.Create instances of
Car and Bicycle and print their descriptions.💡 Why This Matters
🌍 Real World
Protocol extensions let you add common behavior to many types in your app without repeating code. This is useful for apps managing different but related data types.
💼 Career
Understanding protocol extensions is important for Swift developers to write clean, reusable, and maintainable code in iOS and macOS apps.
Progress0 / 4 steps