0
0
Swiftprogramming~30 mins

Protocol as types in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Protocol as Types in Swift
📖 Scenario: You are building a simple app that manages different types of vehicles. Each vehicle can start its engine, but the way it starts might differ. You want to use a protocol to represent any vehicle type and treat them uniformly.
🎯 Goal: Create a protocol called Vehicle with a startEngine() method. Then create two structs, Car and Motorcycle, that conform to Vehicle. Finally, use the protocol as a type to store different vehicles in an array and start their engines.
📋 What You'll Learn
Create a protocol named Vehicle with a method startEngine() that returns a String.
Create a struct Car that conforms to Vehicle and implements startEngine() returning "Car engine started".
Create a struct Motorcycle that conforms to Vehicle and implements startEngine() returning "Motorcycle engine started".
Create an array called vehicles of type [Vehicle] containing one Car and one Motorcycle.
Use a for loop to call startEngine() on each vehicle in vehicles and print the result.
💡 Why This Matters
🌍 Real World
Protocols let you write flexible code that can work with many types sharing the same behavior, like different vehicles in a transport app.
💼 Career
Understanding protocols and using them as types is key for Swift developers to write clean, reusable, and scalable code.
Progress0 / 4 steps
1
Create the Vehicle protocol
Create a protocol called Vehicle with a method startEngine() that returns a String.
Swift
Need a hint?

Use the protocol keyword and define startEngine() as a function returning String.

2
Create Car and Motorcycle structs conforming to Vehicle
Create a struct called Car that conforms to Vehicle and implements startEngine() returning "Car engine started". Also create a struct called Motorcycle that conforms to Vehicle and implements startEngine() returning "Motorcycle engine started".
Swift
Need a hint?

Define structs with struct Name: Vehicle and implement startEngine() returning the exact strings.

3
Create an array of Vehicle type
Create an array called vehicles of type [Vehicle] containing one Car() and one Motorcycle().
Swift
Need a hint?

Use let vehicles: [Vehicle] = [Car(), Motorcycle()] to create the array.

4
Loop through vehicles and print engine start messages
Use a for loop with variable vehicle to iterate over vehicles. Inside the loop, call startEngine() on vehicle and print the returned string.
Swift
Need a hint?

Use for vehicle in vehicles and print(vehicle.startEngine()).