Protocols and extensions
Define capabilities and add behaviour without inheritance.
What you will be able to do
- Use protocols for capabilities.
- Use extensions to organise conformances.
- Provide default implementations sparingly.
- Prefer composition over inheritance.
In plain English
Protocols describe requirements; conforming types provide them. Extensions add methods to existing types, including protocols. This composition model avoids deep inheritance trees.
protocol Describable {
var summary: String { get }
}
extension Lesson: Describable {
var summary: String { "\(title) (\(minutes) min)" }
}Your turn
EasyAdd a conformance
Make Lesson conform to Describable in an extension.
SWIFT · starter
extension Lesson {Check your understanding before moving on.
Knowledge checkQuestion 1
What does a protocol define?
Select an answer to continue
Study tools
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign inFinished reading?
Lock in what you just learned.
0%
Mark this lesson complete to save your place and move one step closer to the certificate.