0
0
Swiftprogramming~5 mins

Protocol declaration syntax in Swift

Choose your learning style9 modes available
Introduction

A protocol in Swift is like a promise that a type will have certain properties or methods. It helps organize code and makes sure things work together smoothly.

When you want different types to share common behavior without sharing code.
When you want to define a blueprint for methods or properties that multiple types must implement.
When you want to write flexible and reusable code that works with many types.
When you want to separate what something does from how it does it.
When you want to use delegation or callbacks in your app.
Syntax
Swift
protocol ProtocolName {
    // property and method requirements
}

The keyword protocol starts the declaration.

Inside the braces, you list what properties or methods any type adopting this protocol must have.

Examples
This protocol requires any type that adopts it to have a drive() method.
Swift
protocol Drivable {
    func drive()
}
This protocol requires a read-only property name of type String.
Swift
protocol Named {
    var name: String { get }
}
This protocol requires a property id that can be read and changed.
Swift
protocol Identifiable {
    var id: Int { get set }
}
Sample Program

This program defines a protocol Greetable with a method greet(). The struct Person adopts this protocol and implements the method. When we create a Person and call greet(), it prints a greeting.

Swift
protocol Greetable {
    func greet()
}

struct Person: Greetable {
    func greet() {
        print("Hello! Nice to meet you.")
    }
}

let someone = Person()
someone.greet()
OutputSuccess
Important Notes

Protocols only describe what is required, not how it works.

Types like classes, structs, and enums can adopt protocols.

Protocols help make your code easier to understand and maintain.

Summary

Protocols define a set of rules (methods or properties) that types must follow.

Use protocol keyword to declare a protocol.

Protocols help write flexible and organized code.