Bird
Raised Fist0
Swiftprogramming~10 mins

Protocol conformance via extension in Swift - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Protocol conformance via extension
Define Protocol
↓
Define Type (struct/class)
↓
Extend Type
↓
Add Protocol Conformance in Extension
↓
Use Type as Protocol
↓
Call Protocol Methods
↓
Execution of Protocol Methods
First, we define a protocol and a type. Then, we extend the type to add protocol conformance. Finally, we use the type as the protocol and call its methods.
Execution Sample
Swift
protocol Greetable {
    func greet() -> String
}

struct Person {
    let name: String
}

extension Person: Greetable {
    func greet() -> String {
        "Hello, \(name)!"
    }
}
This code defines a protocol Greetable, a struct Person, and then extends Person to conform to Greetable by implementing greet().
Execution Table
StepActionEvaluationResult
1Define protocol Greetable with greet()Protocol createdGreetable protocol exists
2Define struct Person with property nameType createdPerson struct exists with name property
3Extend Person to conform to GreetableAdd greet() methodPerson now conforms to Greetable
4Create instance p = Person(name: "Alice")Instance createdp.name = "Alice"
5Call p.greet()Calls greet() from extension"Hello, Alice!" returned
6Assign p to variable of type GreetableType castp as Greetable works
7Call greet() via Greetable variableCalls greet()"Hello, Alice!" returned
💡 All steps complete, protocol conformance via extension works as expected
Variable Tracker
VariableStartAfter Step 4After Step 5Final
pnilPerson(name: "Alice")Person(name: "Alice")Person(name: "Alice")
p.namenil"Alice""Alice""Alice"
greet() outputnilnil"Hello, Alice!""Hello, Alice!"
Key Moments - 3 Insights
Why can we add protocol conformance in an extension instead of in the original struct?
Extensions allow adding protocol conformance separately from the original type definition, as shown in step 3 of the execution_table.
Does the instance p have access to greet() even though it was added in an extension?
Yes, as shown in step 5, p.greet() works because the extension adds the method to Person.
Can we use the instance p as the protocol type Greetable?
Yes, step 6 shows p can be assigned to a Greetable variable and used to call greet().
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the output of p.greet() at step 5?
Anil
B"Hello, Person!"
C"Hello, Alice!"
DCompilation error
💡 Hint
Check the Result column at step 5 in the execution_table
At which step does Person gain conformance to Greetable?
AStep 3
BStep 2
CStep 4
DStep 1
💡 Hint
Look at the Action and Result columns in the execution_table for when conformance is added
If we remove the greet() method from the extension, what happens when calling p.greet() at step 5?
AIt returns "Hello, Alice!" anyway
BCompilation error because Person does not conform
CReturns nil
DRuns but returns empty string
💡 Hint
Refer to the key_moments about protocol conformance and method availability
Concept Snapshot
protocol ProtocolName {
    func method() -> ReturnType
}

struct TypeName { ... }

extension TypeName: ProtocolName {
    func method() -> ReturnType { ... }
}

- Extensions can add protocol conformance
- Methods added in extensions are available on instances
- Enables separation of concerns and cleaner code
Full Transcript
This example shows how to make a Swift type conform to a protocol using an extension. First, we define a protocol named Greetable with a greet() method. Then, we define a struct Person with a name property. Next, we extend Person to conform to Greetable by implementing the greet() method in the extension. We create an instance of Person named p with the name "Alice". Calling p.greet() returns "Hello, Alice!". We can also assign p to a variable of type Greetable and call greet() through that variable. This demonstrates that protocol conformance can be added separately from the original type definition, and methods added in extensions are fully available on instances.

Practice

(1/5)
1. What is the main purpose of using an extension to conform a type to a protocol in Swift?
easy
A. To add protocol requirements to a type without modifying its original definition
B. To create a new subclass from an existing class
C. To override existing methods in a class
D. To declare a new protocol

Solution

  1. Step 1: Understand protocol conformance

    Protocols define a set of methods or properties a type must implement.
  2. Step 2: Role of extensions

    Extensions allow adding these implementations to a type without changing its original code.
  3. Final Answer:

    To add protocol requirements to a type without modifying its original definition -> Option A
  4. Quick Check:

    Extensions add protocol conformance without altering original type [OK]
Hint: Extensions add protocol methods without touching original code [OK]
Common Mistakes:
  • Thinking extensions create subclasses
  • Confusing extensions with method overriding
  • Believing extensions declare new protocols
2. Which of the following is the correct syntax to make a struct Car conform to protocol Drivable using an extension?
easy
A. protocol Drivable extension Car { func drive() { print("Driving") } }
B. struct Car: Drivable { extension { func drive() { print("Driving") } } }
C. extension Drivable: Car { func drive() { print("Driving") } }
D. extension Car: Drivable { func drive() { print("Driving") } }

Solution

  1. Step 1: Identify correct extension syntax

    Extensions use the format: extension TypeName: ProtocolName { ... }.
  2. Step 2: Check each option

    extension Car: Drivable { func drive() { print("Driving") } } correctly extends Car to conform to Drivable and implements drive().
  3. Final Answer:

    extension Car: Drivable { func drive() { print("Driving") } } -> Option D
  4. Quick Check:

    Correct extension syntax = extension Car: Drivable { func drive() { print("Driving") } } [OK]
Hint: Use 'extension Type: Protocol { }' to conform [OK]
Common Mistakes:
  • Placing extension inside struct
  • Swapping type and protocol names
  • Using 'protocol' keyword incorrectly
3. Consider the code below:
protocol Greetable {
    func greet() -> String
}

struct Person {
    let name: String
}

extension Person: Greetable {
    func greet() -> String {
        return "Hello, \(name)!"
    }
}

let p = Person(name: "Anna")
print(p.greet())

What is the output when this code runs?
medium
A. Hello, !
B. Hello, name!
C. "Hello, Anna!"
D. Error: Person does not conform to Greetable

Solution

  1. Step 1: Check protocol conformance

    Person is extended to conform to Greetable by implementing greet() returning "Hello, \(name)!".
  2. Step 2: Analyze output

    Creating Person with name "Anna" and calling greet() returns "Hello, Anna!" which is printed.
  3. Final Answer:

    "Hello, Anna!" -> Option C
  4. Quick Check:

    Extension adds greet() returning personalized string [OK]
Hint: Extension adds greet() returning personalized message [OK]
Common Mistakes:
  • Expecting error due to missing conformance
  • Ignoring string interpolation
  • Assuming default greet() implementation
4. The following code tries to make Rectangle conform to Shape via extension, but it causes a compile error. What is the error?
protocol Shape {
    var area: Double { get }
}

struct Rectangle {
    var width: Double
    var height: Double
}

extension Rectangle: Shape {
    func area() -> Double {
        return width * height
    }
}
medium
A. Method 'area()' should be a computed property, not a function
B. Cannot extend a struct to conform to a protocol
C. Missing initializer in Rectangle
D. Protocol Shape requires a method named 'area()', not a property

Solution

  1. Step 1: Check protocol requirement

    Shape requires a property area of type Double with a getter.
  2. Step 2: Analyze extension implementation

    The extension implements area() as a method, but protocol expects a computed property var area: Double { get }.
  3. Final Answer:

    Method 'area()' should be a computed property, not a function -> Option A
  4. Quick Check:

    Property requirement needs computed property, not method [OK]
Hint: Match protocol property with computed property, not method [OK]
Common Mistakes:
  • Implementing property as method
  • Thinking structs can't conform via extension
  • Ignoring protocol property vs method difference
5. You have a protocol Printable requiring a method printDetails(). You want to add this conformance to an existing class Book without changing its original code. Which approach correctly achieves this and allows printDetails() to print the book's title and author?
class Book {
    let title: String
    let author: String
    init(title: String, author: String) {
        self.title = title
        self.author = author
    }
}
hard
A. class Book: Printable { func printDetails() { print(title + author) } }
B. extension Book: Printable { func printDetails() { print("Title: \(title), Author: \(author)") } }
C. protocol Printable { func printDetails() } extension Printable { func printDetails() { print("No details") } }
D. extension Printable: Book { func printDetails() { print(title + author) } }

Solution

  1. Step 1: Understand requirement

    We want to add Printable conformance to Book without changing Book's original code.
  2. Step 2: Use extension to conform

    extension Book: Printable { func printDetails() { print("Title: \(title), Author: \(author)") } } extends Book to conform to Printable and implements printDetails() accessing Book's properties.
  3. Final Answer:

    extension Book: Printable { func printDetails() { print("Title: \(title), Author: \(author)") } } -> Option B
  4. Quick Check:

    Extension adds protocol conformance and method using existing properties [OK]
Hint: Use extension on class to add protocol methods accessing properties [OK]
Common Mistakes:
  • Trying to modify original class code
  • Incorrectly extending protocol instead of class
  • Not implementing required method
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard