0
0
Swiftprogramming~3 mins

Why Protocol as types in Swift? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could write one piece of code that works perfectly with many different things, no matter how different they are?

The Scenario

Imagine you have different kinds of devices like phones, tablets, and laptops. You want to write code that works with any device, but each device has its own unique features and ways to do things.

If you try to write separate code for each device type everywhere, your code becomes messy and hard to manage.

The Problem

Writing separate code for each device means repeating yourself a lot. It's easy to make mistakes because you have to remember all the differences. When you add a new device, you must change many parts of your code, which is slow and error-prone.

The Solution

Using protocols as types lets you define a common set of features that all devices share. You can write code that works with any device type through this shared protocol, without worrying about the specific device. This keeps your code clean, flexible, and easy to update.

Before vs After
Before
func useDevice(device: Phone) { device.call() }
func useDevice(device: Tablet) { device.call() }
After
protocol Device { func call() }
func useDevice(device: Device) { device.call() }
What It Enables

This lets you write one simple function that works with many different types, making your code easier to read, maintain, and extend.

Real Life Example

Think of a music app that plays songs on different devices. Using protocols as types, the app can play music on phones, tablets, or smart speakers without changing the main code.

Key Takeaways

Protocols let you define shared behavior for different types.

Using protocols as types simplifies code by treating different objects the same way.

This approach makes your code flexible and easier to maintain.