0
0
Swiftprogramming~30 mins

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

Choose your learning style9 modes available
Why protocol-oriented programming matters
📖 Scenario: Imagine you are building a simple app that manages 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 programming helps write flexible and reusable code.
📋 What You'll Learn
Create a protocol named 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 that holds both Car and Bicycle instances
Use a for loop to call start() on each vehicle in the vehicles array
Print output messages showing each vehicle starting and stopping
💡 Why This Matters
🌍 Real World
Protocol-oriented programming is used in Swift to write clean, reusable code that works well with many types. It helps apps stay organized and easy to extend.
💼 Career
Understanding protocols is essential for Swift developers. It is a core skill for building apps that are maintainable and scalable in professional iOS development.
Progress0 / 4 steps
1
Create the Vehicle protocol
Create a protocol named 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(). Then create a struct called Bicycle that also conforms to Vehicle and implements start() and stop().
Swift
Need a hint?

Use struct Car: Vehicle {} and implement the two methods with print statements. Do the same for Bicycle.

3
Create an array of vehicles
Create an array called vehicles that holds instances of Car and Bicycle.
Swift
Need a hint?

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

4
Start all vehicles and print output
Use a for loop with variable vehicle to iterate over vehicles and call start() on each. Then print a message showing each vehicle started.
Swift
Need a hint?

Use for vehicle in vehicles { vehicle.start() } to call start on each vehicle.