Protocol composition lets you combine multiple protocols into one requirement. It helps you say: "I want something that follows these rules together."
Protocol composition in Swift
Introduction
Syntax
Swift
func exampleFunction(param: ProtocolA & ProtocolB) { // code here }
Use the & symbol to combine protocols.
The combined type must conform to all listed protocols.
Examples
Swift
protocol Drivable { func drive() } protocol Flyable { func fly() } func travel(vehicle: Drivable & Flyable) { vehicle.drive() vehicle.fly() }
Swift
protocol Readable { func read() } protocol Writable { func write() } func process(document: Readable & Writable) { document.read() document.write() }
Sample Program
This program defines two protocols, Painter and Singer. The Artist struct follows both. The perform function uses protocol composition to accept anything that can paint and sing. It calls both methods.
Swift
protocol Painter { func paint() } protocol Singer { func sing() } struct Artist: Painter, Singer { func paint() { print("Painting a beautiful picture.") } func sing() { print("Singing a lovely song.") } } func perform(show: Painter & Singer) { show.paint() show.sing() } let artist = Artist() perform(show: artist)
Important Notes
Protocol composition is a way to require multiple behaviors without making a new protocol.
It helps keep code flexible and reusable.
Summary
Protocol composition combines multiple protocols using &.
It lets you require multiple behaviors at once.
Use it to write flexible and clear code.
Practice
1. What does
protocol composition in Swift allow you to do?easy
Solution
Step 1: Understand protocol composition concept
Protocol composition uses the & symbol to combine multiple protocols into one requirement.Step 2: Differentiate from class inheritance
Swift does not support multiple class inheritance, but protocol composition allows combining multiple protocols.Final Answer:
Combine multiple protocols into one requirement using & -> Option DQuick Check:
Protocol composition = Combine protocols with & [OK]
Hint: Remember & joins protocols to require multiple behaviors [OK]
Common Mistakes:
- Confusing protocol composition with class inheritance
- Thinking protocols can inherit from classes
- Assuming protocol composition overrides methods
2. Which of the following is the correct syntax for protocol composition in Swift?
easy
Solution
Step 1: Identify correct usage of protocol composition
Protocol composition is used in type annotations likelet variable: ProtocolA & ProtocolB.Step 2: Check other options for syntax errors
Options B and C misuse protocol inheritance or assignment syntax; D tries class inheritance from protocols incorrectly.Final Answer:
let combined: ProtocolA & ProtocolB -> Option BQuick Check:
Protocol composition syntax = type annotation with & [OK]
Hint: Use & in type declarations, not in protocol inheritance [OK]
Common Mistakes:
- Trying to inherit protocols with & in protocol declaration
- Using = instead of : or &
- Using class inheritance syntax with protocols
3. What will be the output of this Swift code?
protocol A { func foo() }
protocol B { func bar() }
struct S: A, B {
func foo() { print("foo") }
func bar() { print("bar") }
}
func test(x: A & B) {
x.foo()
x.bar()
}
let s = S()
test(x: s)medium
Solution
Step 1: Understand protocol composition parameter
The functiontestrequires an argument conforming to both protocols A and B.Step 2: Check struct S conformance and method calls
S conforms to both A and B, so callingfoo()andbar()prints "foo" and "bar" respectively.Final Answer:
foo bar -> Option CQuick Check:
Both protocol methods called = foo and bar printed [OK]
Hint: Both protocols' methods run when composed type passed [OK]
Common Mistakes:
- Assuming only one protocol's method runs
- Thinking protocol composition causes errors
- Confusing struct conformance with protocol composition
4. Identify the error in this Swift code using protocol composition:
protocol P1 { func p1() }
protocol P2 { func p2() }
func doSomething(x: P1 & P2) {
x.p1()
x.p2()
}
struct MyStruct: P1 {
func p1() { print("p1") }
}
doSomething(x: MyStruct())medium
Solution
Step 1: Check struct conformance to protocols
MyStruct conforms only to P1, missing P2 conformance.Step 2: Understand function parameter requirement
doSomething requires an argument conforming to both P1 and P2, so MyStruct instance is invalid.Final Answer:
MyStruct does not conform to P2, so cannot be passed to doSomething -> Option AQuick Check:
Protocol composition requires all protocols conformed [OK]
Hint: Check all protocols are conformed before passing composed type [OK]
Common Mistakes:
- Passing instance conforming to only one protocol
- Thinking protocol composition allows partial conformance
- Ignoring compiler errors about missing protocol methods
5. Given these protocols and structs:
Which code snippet correctly uses protocol composition to accept only Drawable and Colorful types?
protocol Drawable { func draw() }
protocol Colorful { var color: String { get } }
struct Circle: Drawable, Colorful {
var color: String
func draw() { print("Drawing a \(color) circle") }
}
struct Square: Drawable {
func draw() { print("Drawing a square") }
}Which code snippet correctly uses protocol composition to accept only Drawable and Colorful types?
hard
Solution
Step 1: Identify correct protocol composition syntax
func render(item: Drawable & Colorful) { item.draw() } usesDrawable & Colorfulcorrectly in parameter type.Step 2: Check other options for syntax or logic errors
func render(item: Drawable | Colorful) { item.draw() } uses | which is invalid; C misuses where clause syntax; D uses where clause incorrectly on parameter.Final Answer:
func render(item: Drawable & Colorful) { item.draw() } -> Option AQuick Check:
Use & to combine protocols in function parameters [OK]
Hint: Use & to combine protocols in parameter types, not | or where [OK]
Common Mistakes:
- Using | instead of & for protocol composition
- Misusing where clauses in parameter declarations
- Trying to filter protocol properties in parameter signature
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
