0
0
Swiftprogramming~15 mins

Protocol conformance in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Protocol conformance
📖 Scenario: You are building a simple app that manages different types of vehicles. Each vehicle should be able to describe itself.
🎯 Goal: Create a protocol called Vehicle with a property and a method. Then create a struct that conforms to this protocol and implements the required property and method.
📋 What You'll Learn
Create a protocol named Vehicle with a var name: String { get } property and a func description() -> String method.
Create a struct named Car that conforms to the Vehicle protocol.
Implement the name property and the description() method inside Car.
Print the result of calling description() on an instance of Car.
💡 Why This Matters
🌍 Real World
Protocols help define common behavior for different types, like vehicles, so your app can work with them in a uniform way.
💼 Career
Understanding protocol conformance is essential for writing clean, reusable, and flexible Swift code in professional iOS development.
Progress0 / 4 steps
1
Create the Vehicle protocol
Create a protocol called Vehicle with a read-only property name of type String and a method description() that returns a String.
Swift
Need a hint?

Use the protocol keyword to define a protocol. The property name should be read-only, so use { get }.

2
Create the Car struct conforming to Vehicle
Create a struct named Car that conforms to the Vehicle protocol. Add a stored property name of type String.
Swift
Need a hint?

Use struct Car: Vehicle to conform. Implement the name property as a stored property.

3
Implement the description() method in Car
Inside the Car struct, implement the description() method to return the string "This is a car named \(name).".
Swift
Need a hint?

Return a string using string interpolation to include the name property.

4
Create an instance of Car and print its description
Create a constant myCar of type Car with the name "SwiftCar". Then print the result of calling myCar.description().
Swift
Need a hint?

Create the instance with Car(name: "SwiftCar") and print the description.