0
0
iOS Swiftmobile~3 mins

Why Protocols in iOS Swift? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could make different parts of your app talk the same language without rewriting code over and over?

The Scenario

Imagine you are building an app with many different types of objects, like buttons, sliders, and switches. Each object needs to respond to user taps, but you have to write separate code for each one to handle taps.

The Problem

Writing separate tap-handling code for every object is slow and error-prone. If you want to add a new object type, you must remember to add tap code again. This leads to repeated code and bugs when you forget or do it inconsistently.

The Solution

Protocols let you define a common set of behaviors that many different objects can share. You write the tap-handling code once in the protocol, and any object that adopts the protocol promises to implement that behavior. This keeps your code clean and consistent.

Before vs After
Before
class Button {
  func tap() { /* handle tap */ }
}
class Slider {
  func tap() { /* handle tap differently */ }
}
After
protocol Tappable {
  func tap()
}
class Button: Tappable {
  func tap() { /* handle tap */ }
}
class Slider: Tappable {
  func tap() { /* handle tap differently */ }
}
What It Enables

Protocols enable you to write flexible, reusable code that works with many object types through a shared interface.

Real Life Example

In iOS apps, protocols let you create delegate patterns where one object tells another what happened, like a table view telling its delegate when a row is selected.

Key Takeaways

Protocols define shared behaviors for different objects.

They reduce repeated code and bugs.

They make your app easier to extend and maintain.