0
0
Swiftprogramming~20 mins

Protocol extensions with default implementations in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
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() -> String
Add a protocol extension for Vehicle that provides a default implementation of description()
Create a struct Car that conforms to Vehicle and uses the default description
Create a struct Bicycle that conforms to Vehicle and provides its own description() implementation
Print 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
1
Create the Vehicle protocol
Create a protocol called Vehicle with a method func description() -> String.
Swift
Need a hint?

Use the protocol keyword and declare the method signature without a body.

2
Add a default implementation with a protocol extension
Add a protocol extension for Vehicle that provides a default implementation of description() returning the string "This is a vehicle.".
Swift
Need a hint?

Use extension Vehicle and implement description() with the return string.

3
Create Car and Bicycle structs conforming to Vehicle
Create a struct called Car that conforms to Vehicle and uses the default description(). Then create a struct called Bicycle that conforms to Vehicle and provides its own description() returning "This is a bicycle.".
Swift
Need a hint?

Define Car without adding description() to use the default. Define Bicycle with its own description() method.

4
Print descriptions of Car and Bicycle
Create instances of Car and Bicycle. Then print the result of calling description() on each instance.
Swift
Need a hint?

Create variables myCar and myBike for the instances. Use print() to show their descriptions.