← Back to Swift Course | Chapter 9: Inheritance & Protocols | Lesson 5 of 7

Protocol Conformance

Conformance is a type actually keeping its promise, by providing real code for every item on the protocol's checklist.

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

markup
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())

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

markup
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)
Common Mistakes
  1. Forgetting a property requirement's { get } vs { get set } distinction -- { get set } requires the conforming type's property to be mutable.
  2. Declaring conformance (: ProtocolName) but forgetting to actually implement one of the required methods, causing a compile error.
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.