Protocols are a way of describing what properties and methods something must have. You then tell Swift which types use that protocol – a process known as adopting or conforming to a protocol.
protocol identifiable {
var id: String { get set }
}
struct User: Identifiable {
var id: String
}
func displayId(thing: Identifiable) {
print("my ID is \(thing.id)")
}
One protocol can inherit from another in a process known as protocol inheritance. Unlike with classes, you can inherit from multiple protocols at the same time before you add your own customizations on top.
protocol Payable {
func calclulateWages() -> Int
}
protocol NeedsTraining {
func study()
}
protocol HasVacation {
func takeVacation(days: Int)
}
protocol Employee: Payable, NeedsTraining, HasVacation {}
Extensions allow you to add methods to existing types, to make them do things they weren’t originally designed to do.
Extensions in SwiftUI allow you to add functionality to existing types without modifying their original source code. This means you can enhance built-in types, your own custom views, and even types from external libraries.
Key points: