0
0
Swiftprogramming~5 mins

Protocol requirements (methods and properties) in Swift

Choose your learning style9 modes available
Introduction

Protocols define a set of rules that classes, structs, or enums must follow. They make sure certain methods and properties are present.

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 define a blueprint for methods and properties without implementation.
When you want to ensure certain methods or properties exist in multiple types.
When you want to use polymorphism to treat different types the same way.
Syntax
Swift
protocol SomeProtocol {
    var mustHaveProperty: Int { get set }
    func requiredMethod() -> String
}

Properties in protocols can be read-only ({ get }) or read-write ({ get set }).

Methods in protocols only declare the signature, not the body.

Examples
This protocol requires a read-only property and a method.
Swift
protocol Vehicle {
    var numberOfWheels: Int { get }
    func drive()
}
This protocol requires a read-write property and a method that returns a string.
Swift
protocol Person {
    var name: String { get set }
    func greet() -> String
}
This protocol only requires a method with a parameter.
Swift
protocol Logger {
    func log(message: String)
}
Sample Program

This program defines a protocol Animal with a property and a method. The struct Dog follows the protocol by implementing the property and method. It then prints the dog's name and sound.

Swift
protocol Animal {
    var name: String { get }
    func sound() -> String
}

struct Dog: Animal {
    var name: String
    func sound() -> String {
        return "Woof!"
    }
}

let myDog = Dog(name: "Buddy")
print("\(myDog.name) says \(myDog.sound())")
OutputSuccess
Important Notes

When a type adopts a protocol, it must implement all required methods and properties.

Properties can be declared as { get } or { get set } to control if they are read-only or read-write.

Protocols help write code that is easier to test and maintain.

Summary

Protocols define required methods and properties without implementation.

Types that adopt protocols must implement all requirements.

Use protocols to create flexible and reusable code.