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