Protocol Conformance
Conformance is a type actually keeping its promise, by providing real code for every item on the protocol's checklist.
In this page:
Implementing All Requirements
To conform to a protocol, a type must provide a real implementation for every property and method the protocol lists as required.
Example: Implementing All Requirements
protocol Describable {
var description: String { get }
func summary() -> String
}
struct Book: Describable {
var title: String
var description: String {
return "Book titled \(title)"
}
func summary() -> String {
return "Summary: \(description)"
}
}
let book = Book(title: "Swift Basics")
print(book.summary())
Login to try C/C++/Java/PHP code in the editor
Conforming via an Extension
Protocol conformance can be added to an existing type through an extension, keeping the conformance code separate from the original type definition.
Example: Conforming via an Extension
protocol Named {
var displayName: String { get }
}
struct Product {
var title: String
}
extension Product: Named {
var displayName: String {
return "Product: \(title)"
}
}
let product = Product(title: "Headphones")
print(product.displayName)
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Forgetting a property requirement's
{ get }vs{ get set }distinction --{ get set }requires the conforming type's property to be mutable. - Declaring conformance (
: ProtocolName) but forgetting to actually implement one of the required methods, causing a compile error. - Trying to conform a type to a protocol via an extension while also adding new stored properties there; extensions cannot add stored properties.
Chapter Summary
- A type must implement every property and method a protocol requires to conform.
{ get }in a protocol means read-only access is required;{ get set }requires a settable property too.- Conformance can be declared directly on the type or added later via an extension.
- The compiler checks conformance at compile time, so missing requirements are caught immediately.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: