Protocols let us define a set of rules or features. Using a protocol as a type means we can work with any object that follows those rules, without caring about its exact kind.
0
0
Protocol as types in Swift
Introduction
When you want to write a function that can accept different kinds of objects, as long as they share some behavior.
When you want to store different objects in the same list or variable, but only care about the shared features.
When you want to hide the exact type of an object and only expose what it can do.
When you want to make your code flexible and easy to change later.
Syntax
Swift
protocol SomeProtocol { func doSomething() } func useProtocolType(item: SomeProtocol) { item.doSomething() }
You use the protocol name as a type to accept any object that conforms to it.
This helps write flexible and reusable code.
Examples
Here,
Greetable is a protocol. The function sayHello accepts any object that can greet.Swift
protocol Greetable { func greet() } struct Person: Greetable { func greet() { print("Hello!") } } func sayHello(to someone: Greetable) { someone.greet() }
We create an array of
Drawable objects. Each can be drawn, even if they are different shapes.Swift
protocol Drawable { func draw() } class Circle: Drawable { func draw() { print("Drawing a circle") } } let shapes: [Drawable] = [Circle(), Circle()] for shape in shapes { shape.draw() }
Sample Program
This program defines a Vehicle protocol. Both Car and Bike follow it. The function startJourney accepts any Vehicle and calls its drive method.
Swift
protocol Vehicle { func drive() } struct Car: Vehicle { func drive() { print("Car is driving") } } struct Bike: Vehicle { func drive() { print("Bike is driving") } } func startJourney(with vehicle: Vehicle) { vehicle.drive() } let myCar = Car() let myBike = Bike() startJourney(with: myCar) startJourney(with: myBike)
OutputSuccess
Important Notes
Protocols as types let you write code that works with many kinds of objects.
Only the methods and properties in the protocol are accessible when using the protocol as a type.
If you need to access something specific to a concrete type, you must cast it.
Summary
Protocols define a set of features or rules.
Using a protocol as a type means any object following those rules can be used.
This makes your code flexible and easier to maintain.