0
0
Swiftprogramming~3 mins

Why Protocol declaration syntax in Swift? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could write a single set of rules that many different things promise to follow perfectly?

The Scenario

Imagine you want to create several types of objects that share some common behavior, like different vehicles that can all start and stop. Without a clear plan, you write similar code for each vehicle separately.

The Problem

Writing the same methods over and over is slow and easy to forget or make mistakes. If you want to change the behavior, you must update every single type manually, which is tiring and error-prone.

The Solution

Protocols let you define a blueprint of methods and properties that many types can follow. This way, you write the rules once, and all types that adopt the protocol promise to follow them, making your code cleaner and easier to manage.

Before vs After
Before
class Car {
  func start() { /* code */ }
  func stop() { /* code */ }
}

class Bike {
  func start() { /* code */ }
  func stop() { /* code */ }
}
After
protocol Vehicle {
  func start()
  func stop()
}

class Car: Vehicle {
  func start() { /* code */ }
  func stop() { /* code */ }
}

class Bike: Vehicle {
  func start() { /* code */ }
  func stop() { /* code */ }
}
What It Enables

Protocols enable you to write flexible and reusable code by defining shared behavior that many types can adopt.

Real Life Example

Think of a remote control that works with any TV brand because all TVs follow the same control protocol. Similarly, protocols in Swift let different types work together smoothly.

Key Takeaways

Protocols define a set of rules for methods and properties.

They help avoid repeating code and reduce errors.

Many types can adopt the same protocol to share behavior.