You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Protocol-oriented programming is a cornerstone of Swift. This lesson covers protocols, protocol conformance, extensions, and how they combine to create flexible, composable designs.
A protocol defines a blueprint of methods, properties, and other requirements:
protocol Describable {
var description: String { get }
func summarise() -> String
}
struct Person: Describable {
var name: String
var age: Int
var description: String {
"\(name), age \(age)"
}
func summarise() -> String {
"Person: \(description)"
}
}
let alice = Person(name: "Alice", age: 30)
print(alice.summarise()) // "Person: Alice, age 30"
protocol Named {
var name: String { get } // read-only requirement
}
protocol Editable {
var content: String { get set } // read-write requirement
}
protocol Toggleable {
mutating func toggle()
}
struct LightSwitch: Toggleable {
var isOn = false
mutating func toggle() {
isOn.toggle()
}
}
protocol Area {
var area: Double { get }
}
struct Circle: Area {
var radius: Double
var area: Double { .pi * radius * radius }
}
struct Rectangle: Area {
var width: Double
var height: Double
var area: Double { width * height }
}
// Use the protocol as a type
let shapes: [Area] = [
Circle(radius: 5),
Rectangle(width: 4, height: 6)
]
for shape in shapes {
print("Area: \(shape.area)")
}
Protocols can inherit from other protocols:
protocol Identifiable {
var id: String { get }
}
protocol Named {
var name: String { get }
}
protocol User: Identifiable, Named {
var email: String { get }
}
struct AppUser: User {
var id: String
var name: String
var email: String
}
Extensions add new functionality to existing types without modifying their source code:
extension Int {
var isEven: Bool { self % 2 == 0 }
var isOdd: Bool { !isEven }
var squared: Int { self * self }
}
print(4.isEven) // true
print(7.squared) // 49
extension String {
func reversed() -> String {
String(self.reversed() as ReversedCollection<String>)
}
var wordCount: Int {
self.split(separator: " ").count
}
}
print("Hello World".wordCount) // 2
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.