0
0
iOS Swiftmobile~5 mins

Protocols in iOS Swift

Choose your learning style9 modes available
Introduction

Protocols help you define a set of rules or actions that different parts of your app can follow. They make your code organized and easy to change.

When you want different objects to share common behavior without sharing code.
When you want to make sure a class or struct has certain functions or properties.
When you want to write flexible code that can work with many types.
When you want to separate what something does from how it does it.
Syntax
iOS Swift
protocol ProtocolName {
    func someFunction()
    var someProperty: String { get set }
}

Protocols list methods and properties without giving their code.

Classes, structs, or enums can adopt protocols by implementing the required parts.

Examples
A simple protocol requiring a drive() function.
iOS Swift
protocol Drivable {
    func drive()
}
This protocol requires a read-only name property.
iOS Swift
protocol Named {
    var name: String { get }
}
A struct adopting Drivable and providing the drive() function.
iOS Swift
struct Car: Drivable {
    func drive() {
        print("Car is driving")
    }
}
Sample App

This program defines a protocol Greetable with a greet() function. The Person class adopts it and implements greet() to say hello with a name.

iOS Swift
protocol Greetable {
    func greet()
}

class Person: Greetable {
    var name: String
    init(name: String) {
        self.name = name
    }
    func greet() {
        print("Hello, my name is \(name)")
    }
}

let person = Person(name: "Anna")
person.greet()
OutputSuccess
Important Notes

Protocols do not contain code, only the rules to follow.

Use protocols to write flexible and reusable code.

Multiple protocols can be adopted by one class or struct.

Summary

Protocols define a blueprint of methods and properties.

Classes, structs, and enums can adopt protocols by implementing required parts.

Protocols help keep code organized and flexible.