0
0
Swiftprogramming~15 mins

Protocol conformance via extension in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Protocol conformance via extension
📖 Scenario: Imagine you are building a simple app that manages different types of vehicles. You want all vehicles to be able to describe themselves with a short message.
🎯 Goal: You will create a protocol called VehicleDescription that requires a description method. Then, you will make a struct Car conform to this protocol using an extension. Finally, you will print the description of a Car instance.
📋 What You'll Learn
Create a protocol named VehicleDescription with a method func description() -> String
Create a struct named Car with a property model of type String
Use an extension to make Car conform to VehicleDescription
Implement the description() method inside the extension to return a string describing the car model
Create an instance of Car with model "Tesla Model S"
Print the result of calling description() on the Car instance
💡 Why This Matters
🌍 Real World
Protocols help define common behavior for different types in apps, making code easier to organize and extend.
💼 Career
Understanding protocol conformance via extensions is essential for writing clean, modular Swift code in iOS development.
Progress0 / 4 steps
1
Create the protocol and struct
Create a protocol called VehicleDescription with a method func description() -> String. Then create a struct called Car with a property model of type String.
Swift
Need a hint?

Protocols define methods that types must implement. Structs hold data like the car model.

2
Add protocol conformance via extension
Use an extension to make Car conform to VehicleDescription. Implement the description() method inside the extension to return a string like "Car model: Tesla Model S" using the model property.
Swift
Need a hint?

Extensions add protocol conformance outside the original struct. Use string interpolation to include the model.

3
Create a Car instance
Create a constant called myCar of type Car and set its model property to "Tesla Model S".
Swift
Need a hint?

Use let to create a constant instance with the exact model string.

4
Print the car description
Write a print statement to display the result of calling description() on myCar.
Swift
Need a hint?

Call description() on myCar inside print().