Swift — Protocols
Basic protocol
protocol Drawable {
func draw()
}
class Circle: Drawable {
func draw() {
print("Drawing circle")
}
}
Protocol with properties
protocol Named {
var name: String { get }
}
protocol Aged {
var age: Int { get }
}
class Person: Named, Aged {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
}
Protocol with default implementation
protocol Greetable {
func greet()
}
extension Greetable {
func greet() {
print("Hello!")
}
}
struct Robot: Greetable {
// Uses default implementation
}
Robot().greet() // Hello!
Protocol inheritance
protocol Printable {
func printInfo()
}
protocol Loggable: Printable {
func log()
}
class Document: Loggable {
func printInfo() { print("Printing document") }
func log() { print("Logging document") }
}
Protocol extensions
protocol Collection {
var count: Int { get }
var isEmpty: Bool { get }
}
extension Collection {
var isEmpty: Bool { count == 0 }
}
Mini Practice
Write Swift code that:
- Defines a protocol with properties and methods
- Adds a default implementation with an extension
- Uses protocol inheritance
- Creates a protocol extension
Up Next
In the next lesson, you'll learn about Optionals — handling missing values.
Related Topics
Frequently Asked Questions about Protocols
What is Protocols in Swift?
Protocols is a fundamental concept in Swift. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Protocols?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Protocols.
Why is Protocols important in Swift?
Protocols is essential for Swift development. Understanding this concept will help you write better code and solve real-world problems more effectively.