0
0
Swiftprogramming~30 mins

Protocol extensions for shared behavior in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
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
1
Create the Vehicle protocol
Create a protocol called Vehicle with a read-only name property of type String and a method description() that returns a String.
Swift
Need a hint?

Protocols define what properties and methods a type must have. Use protocol Vehicle { ... }.

2
Add a protocol extension with default description
Add a protocol extension for Vehicle that provides a default implementation of the description() method. It should return the string "This is a vehicle named \(name).".
Swift
Need a hint?

Use extension Vehicle { func description() -> String { ... } } to add shared behavior.

3
Create Car and Bicycle structs conforming to Vehicle
Create a struct called Car with a name property of type String that conforms to Vehicle. Also create a struct called Bicycle with a name property of type String that conforms to Vehicle.
Swift
Need a hint?

Use struct Car: Vehicle { let name: String } and similarly for Bicycle.

4
Create instances and print descriptions
Create a constant myCar as an instance of Car with the name "Tesla". Create a constant myBike as an instance of Bicycle with the name "Mountain Bike". Then print the result of calling description() on both myCar and myBike.
Swift
Need a hint?

Create instances with let myCar = Car(name: "Tesla") and print with print(myCar.description()).