What if you could write one piece of code that works perfectly with many different things, no matter how different they are?
Why Protocol as types in Swift? - Purpose & Use Cases
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.
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.
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.
func useDevice(device: Phone) { device.call() }
func useDevice(device: Tablet) { device.call() }protocol Device { func call() }
func useDevice(device: Device) { device.call() }This lets you write one simple function that works with many different types, making your code easier to read, maintain, and extend.
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.
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.