0
0
Swiftprogramming~5 mins

Protocol conformance in Swift

Choose your learning style9 modes available
Introduction

Protocols define a set of rules or features that a type must follow. Protocol conformance means a type agrees to follow those rules.

When you want different types to share common behavior.
When you want to write flexible code that works with many types.
When you want to ensure a type has certain properties or methods.
When you want to organize your code by defining clear contracts.
When you want to use polymorphism to treat different types the same way.
Syntax
Swift
protocol SomeProtocol {
    func someMethod()
}

struct SomeType: SomeProtocol {
    func someMethod() {
        // implementation
    }
}

A protocol lists methods or properties without implementation.

A type (class, struct, enum) uses a colon and the protocol name to conform.

Examples
A struct conforms to the Greetable protocol by implementing the greet() method.
Swift
protocol Greetable {
    func greet()
}

struct Person: Greetable {
    func greet() {
        print("Hello!")
    }
}
A class conforms to Describable by providing a read-only description property.
Swift
protocol Describable {
    var description: String { get }
}

class Car: Describable {
    var description: String {
        return "A fast car"
    }
}
A struct conforms by having a stored property matching the protocol requirement.
Swift
protocol Identifiable {
    var id: Int { get set }
}

struct User: Identifiable {
    var id: Int
}
Sample Program

This program defines a Vehicle protocol with a startEngine method. Motorcycle conforms by implementing startEngine. When called, it prints a message.

Swift
protocol Vehicle {
    func startEngine()
}

struct Motorcycle: Vehicle {
    func startEngine() {
        print("Motorcycle engine started")
    }
}

let bike = Motorcycle()
bike.startEngine()
OutputSuccess
Important Notes

All required methods and properties must be implemented to conform.

Protocols can be used as types to hold any conforming instance.

Conformance helps write reusable and organized code.

Summary

Protocols define rules for types to follow.

Types conform by implementing required methods and properties.

Protocol conformance enables flexible and clear code design.