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 }
}
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.