0
0
Swiftprogramming~10 mins

Protocol composition in practice in Swift - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Protocol composition in practice
Define Protocol A
Define Protocol B
Create Struct/Class conforming to A & B
Use protocol composition (A & B) as type
Call methods from both protocols
Observe combined behavior
This flow shows how two protocols are defined, combined, and used together in Swift to create flexible types.
Execution Sample
Swift
protocol A {
    func greet()
}
protocol B {
    func farewell()
}
struct Person: A, B {
    func greet() { print("Hello") }
    func farewell() { print("Goodbye") }
}
func welcome(_ entity: A & B) {
    entity.greet()
    entity.farewell()
}
let p = Person()
welcome(p)
This code defines two protocols, a struct conforming to both, and a function that accepts a parameter conforming to both protocols, then calls their methods.
Execution Table
StepActionEvaluationResult
1Define protocol A with greet()protocol A createdProtocol A ready
2Define protocol B with farewell()protocol B createdProtocol B ready
3Define struct Person conforming to A & BPerson struct createdPerson has greet() and farewell()
4Create instance p of Personp = Person()p is ready with both methods
5Call welcome(p) with p as A & Bwelcome(p) calledInside welcome: entity.greet() and entity.farewell()
6entity.greet() executesprint("Hello")Output: Hello
7entity.farewell() executesprint("Goodbye")Output: Goodbye
8Function welcome endsreturnExecution complete
💡 All steps executed; program ends after printing greetings.
Variable Tracker
VariableStartAfter Step 4After Step 5Final
pundefinedPerson instance with greet and farewellPassed as A & B to welcomeNo change after function ends
entityundefinedundefinedReferences p as A & BNo change after function ends
Key Moments - 3 Insights
Why can the function welcome accept a parameter typed as A & B?
Because the parameter uses protocol composition (A & B), it requires the argument to conform to both protocols, ensuring both greet() and farewell() methods are available, as shown in execution_table step 5.
What happens if Person only conformed to protocol A but not B?
The function welcome would not accept Person as argument because it requires both protocols. This would cause a compile-time error before step 5.
Why do we see both "Hello" and "Goodbye" printed?
Because welcome calls both entity.greet() and entity.farewell(), and Person implements both methods, as shown in execution_table steps 6 and 7.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 6, what method is called?
Awelcome()
Bfarewell()
Cgreet()
DPerson initializer
💡 Hint
Check the 'Action' and 'Evaluation' columns at step 6 in execution_table.
At which step does the instance 'p' get created?
AStep 3
BStep 4
CStep 5
DStep 6
💡 Hint
Look for the step mentioning 'Create instance p of Person' in execution_table.
If Person did not conform to protocol B, what would happen at step 5?
ACompile-time error due to missing protocol conformance
Bwelcome(p) would run normally
COnly greet() would be called
Dfarewell() would print default message
💡 Hint
Refer to key_moments about protocol composition and conformance requirements.
Concept Snapshot
Protocol composition combines multiple protocols into one type.
Use syntax: func example(param: A & B) { }.
The parameter must conform to all protocols.
Allows flexible, reusable code.
Methods from all protocols are accessible.
Compile-time safety ensures conformance.
Full Transcript
This example shows how Swift protocols can be combined using protocol composition. Two protocols, A and B, are defined with methods greet() and farewell(). A struct Person conforms to both protocols by implementing these methods. A function welcome accepts a parameter typed as A & B, meaning it requires an object that conforms to both protocols. When welcome is called with a Person instance, it can safely call both greet() and farewell() methods. The execution table traces each step: defining protocols, creating the struct, instantiating Person, calling welcome, and printing outputs. The variable tracker shows how the instance 'p' and parameter 'entity' change during execution. Key moments clarify why protocol composition works and what happens if conformance is missing. The visual quiz tests understanding of method calls, instance creation, and conformance errors. The concept snapshot summarizes the syntax and benefits of protocol composition in Swift.