0
0
Swiftprogramming~30 mins

Why protocol-oriented design matters in Swift - See It in Action

Choose your learning style9 modes available
Why protocol-oriented design matters
📖 Scenario: Imagine you are building a simple app to manage different types of vehicles. Each vehicle can start and stop, but they do these actions differently. You want a clean way to organize this behavior so you can add more vehicle types easily in the future.
🎯 Goal: You will create a protocol to define common vehicle actions, then make different vehicle types conform to this protocol. This shows why protocol-oriented design helps keep code simple and flexible.
📋 What You'll Learn
Create a protocol called Vehicle with two methods: start() and stop()
Create a struct called Car that conforms to Vehicle and implements start() and stop()
Create a struct called Bicycle that conforms to Vehicle and implements start() and stop()
Create an array called vehicles containing one Car and one Bicycle
Use a for loop to call start() and stop() on each vehicle in the vehicles array
Print messages inside each start() and stop() method to show which vehicle is starting or stopping
💡 Why This Matters
🌍 Real World
Protocol-oriented design is used in apps to organize code so different objects can share behavior without repeating code. For example, many types of vehicles or UI elements can follow the same protocol to simplify how the app controls them.
💼 Career
Understanding protocol-oriented design is important for Swift developers because it helps write clean, reusable, and flexible code. Many iOS apps and frameworks use protocols to manage complex behaviors in a simple way.
Progress0 / 4 steps
1
Create the Vehicle protocol
Create a protocol called Vehicle with two methods: start() and stop().
Swift
Need a hint?

Protocols define a blueprint of methods. Use protocol Vehicle {} and add func start() and func stop() inside.

2
Create Car and Bicycle structs conforming to Vehicle
Create a struct called Car that conforms to Vehicle and implements start() and stop() methods. Then create a struct called Bicycle that also conforms to Vehicle and implements start() and stop() methods.
Swift
Need a hint?

Use struct Car: Vehicle {} and inside add func start() and func stop() with print statements. Do the same for Bicycle.

3
Create an array of vehicles
Create an array called vehicles containing one Car() and one Bicycle().
Swift
Need a hint?

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

4
Use a loop to start and stop all vehicles
Use a for loop with variable vehicle to iterate over vehicles. Inside the loop, call vehicle.start() and vehicle.stop(). Print the output.
Swift
Need a hint?

Use for vehicle in vehicles { vehicle.start(); vehicle.stop() } to run the methods on each vehicle.