Member-only story
All About Protocol
3 min readJan 6, 2025
1. What is a Protocol?
A protocol defines a blueprint of methods, properties, and other requirements for conforming types.
Syntax:
protocol ProtocolName {
// Property requirements
var propertyName: PropertyType { get set } // { get } for read-only
// Method requirements
func methodName(param: ParamType) -> ReturnType
}
2. Implementing Protocols
A type (class, struct, enum) conforms to a protocol by implementing all its requirements.
Example:
protocol Greetable {
var message: String { get }
func greet()
}
struct Person: Greetable {
var message: String
func greet() {
print(message)
}
}
let person = Person(message: "Hello, Protocol!")
person.greet() // Output: Hello, Protocol!
3. Property Requirements
Protocols can require properties to be implemented.
Syntax:
protocol Example {
var readOnlyProperty: Int { get }
var readWriteProperty: String { get set }
}
- Read-Only (
{ get }
): Only requires a getter. - Read-Write (
{ get set }
): Requires both a getter and setter.
4. Method Requirements
Protocols define methods without implementation.