Bird
Raised Fist0
Swiftprogramming~20 mins

Protocol composition in Swift - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Protocol Composition Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of protocol composition with method calls
What is the output of the following Swift code using protocol composition?
Swift
protocol A {
    func greet() -> String
}

protocol B {
    func farewell() -> String
}

struct Person: A, B {
    func greet() -> String { "Hello" }
    func farewell() -> String { "Goodbye" }
}

func communicate(with entity: A & B) {
    print(entity.greet())
    print(entity.farewell())
}

let p = Person()
communicate(with: p)
AGoodbye
BHello
CHello\nGoodbye
DCompilation error
Attempts:
2 left
💡 Hint
Remember that protocol composition requires the instance to conform to all protocols listed.
❓ Predict Output
intermediate
2:00remaining
Result of accessing properties in protocol composition
What will be printed when running this Swift code that uses protocol composition with properties?
Swift
protocol X {
    var xValue: Int { get }
}

protocol Y {
    var yValue: Int { get }
}

struct Point: X, Y {
    var xValue: Int
    var yValue: Int
}

func printSum(of point: X & Y) {
    print(point.xValue + point.yValue)
}

let pt = Point(xValue: 3, yValue: 7)
printSum(of: pt)
ACompilation error
B37
C0
D10
Attempts:
2 left
💡 Hint
Check how the sum of the two property values is calculated.
🔧 Debug
advanced
2:00remaining
Identify the error in protocol composition usage
What error does this Swift code produce and why?
Swift
protocol P1 {
    func foo()
}

protocol P2 {
    func bar()
}

struct S: P1 {
    func foo() { print("foo") }
}

func test(param: P1 & P2) {
    param.foo()
    param.bar()
}

let s = S()
test(param: s)
AError: 'S' does not conform to protocol 'P2'
BRuntime error: method 'bar' not found
CCompilation error: missing return in function
DNo error, prints 'foo' and 'bar'
Attempts:
2 left
💡 Hint
Check which protocols the struct conforms to and what the function requires.
🧠 Conceptual
advanced
2:00remaining
Understanding protocol composition with class inheritance
Given these Swift declarations, what is true about the variable 'obj' declared below?
Swift
protocol Alpha {
    func alphaMethod()
}

protocol Beta {
    func betaMethod()
}

class Base: Alpha {
    func alphaMethod() { print("Alpha") }
}

class Derived: Base, Beta {
    func betaMethod() { print("Beta") }
}

let obj: Alpha & Beta = Derived()
A'obj' can only call betaMethod()
B'obj' can call both alphaMethod() and betaMethod()
C'obj' cannot call either method
D'obj' can only call alphaMethod()
Attempts:
2 left
💡 Hint
Consider what protocols 'obj' is declared to conform to and the actual class instance.
❓ Predict Output
expert
3:00remaining
Output of complex protocol composition with extensions
What is the output of this Swift code involving protocol composition and protocol extensions?
Swift
protocol First {
    func action() -> String
}

protocol Second {
    func action() -> String
}

extension First {
    func action() -> String { "First" }
}

extension Second {
    func action() -> String { "Second" }
}

struct Combo: First, Second {
    func action() -> String { "Combo" }
}

func performAction(on obj: First & Second) {
    print(obj.action())
}

let c = Combo()
performAction(on: c)
ACombo
BFirst
CSecond
DCompilation error due to ambiguity
Attempts:
2 left
💡 Hint
Check which implementation of action() is called when the struct provides its own.

Practice

(1/5)
1. What does protocol composition in Swift allow you to do?
easy
A. Override methods from multiple protocols automatically
B. Create a new class that inherits from multiple classes
C. Define a protocol that inherits from a single class
D. Combine multiple protocols into one requirement using &

Solution

  1. Step 1: Understand protocol composition concept

    Protocol composition uses the & symbol to combine multiple protocols into one requirement.
  2. Step 2: Differentiate from class inheritance

    Swift does not support multiple class inheritance, but protocol composition allows combining multiple protocols.
  3. Final Answer:

    Combine multiple protocols into one requirement using & -> Option D
  4. Quick 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
A. protocol Combined = ProtocolA & ProtocolB
B. let combined: ProtocolA & ProtocolB
C. protocol Combined: ProtocolA & ProtocolB {}
D. class Combined: ProtocolA & ProtocolB {}

Solution

  1. Step 1: Identify correct usage of protocol composition

    Protocol composition is used in type annotations like let variable: ProtocolA & ProtocolB.
  2. 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.
  3. Final Answer:

    let combined: ProtocolA & ProtocolB -> Option B
  4. Quick 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
A. bar
B. foo
C. foo bar
D. Compilation error

Solution

  1. Step 1: Understand protocol composition parameter

    The function test requires an argument conforming to both protocols A and B.
  2. Step 2: Check struct S conformance and method calls

    S conforms to both A and B, so calling foo() and bar() prints "foo" and "bar" respectively.
  3. Final Answer:

    foo bar -> Option C
  4. Quick 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
A. MyStruct does not conform to P2, so cannot be passed to doSomething
B. Syntax error in protocol composition declaration
C. Missing implementation of p2() in doSomething function
D. doSomething should accept only one protocol, not composition

Solution

  1. Step 1: Check struct conformance to protocols

    MyStruct conforms only to P1, missing P2 conformance.
  2. Step 2: Understand function parameter requirement

    doSomething requires an argument conforming to both P1 and P2, so MyStruct instance is invalid.
  3. Final Answer:

    MyStruct does not conform to P2, so cannot be passed to doSomething -> Option A
  4. Quick 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:
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
A. func render(item: Drawable & Colorful) { item.draw() }
B. func render(item: Drawable | Colorful) { item.draw() }
C. func render(item: Drawable) where item: Colorful { item.draw() }
D. func render(item: Drawable & Colorful) where item.color != "" { item.draw() }

Solution

  1. Step 1: Identify correct protocol composition syntax

    func render(item: Drawable & Colorful) { item.draw() } uses Drawable & Colorful correctly in parameter type.
  2. 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.
  3. Final Answer:

    func render(item: Drawable & Colorful) { item.draw() } -> Option A
  4. Quick 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 strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard