Bird
Raised Fist0
Swiftprogramming~20 mins

Protocol composition in practice 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 this Swift code using protocol composition?
Swift
protocol A {
    func greet()
}

protocol B {
    func greet()
}

struct Person: A, B {
    func greet() {
        print("Hello from Person")
    }
}

func welcome(_ entity: A & B) {
    entity.greet()
}

let p = Person()
welcome(p)
ARuntime error
BNo output
CHello from Person
DCompile-time error due to ambiguous greet()
Attempts:
2 left
💡 Hint
Think about how protocol composition works when both protocols have the same method.
❓ Predict Output
intermediate
2:00remaining
Result of protocol composition with property requirements
What will be printed when this Swift code runs?
Swift
protocol Named {
    var name: String { get }
}

protocol Aged {
    var age: Int { get }
}

struct User: Named, Aged {
    var name: String
    var age: Int
}

func describe(_ entity: Named & Aged) {
    print("\(entity.name) is \(entity.age) years old.")
}

let user = User(name: "Alice", age: 30)
describe(user)
ARuntime error: Missing property implementation
BAlice is 30 years old.
CCompile-time error: Cannot use protocol composition with properties
DAlice is years old.
Attempts:
2 left
💡 Hint
Check how protocol composition works with properties.
❓ Predict Output
advanced
2:00remaining
Output of protocol composition with class and protocol inheritance
What is the output of this Swift code involving protocol composition and class inheritance?
Swift
protocol P1 {
    func action()
}

protocol P2 {
    func action()
}

class Base: P1 {
    func action() {
        print("Base action")
    }
}

class Derived: Base, P2 {
    override func action() {
        print("Derived action")
    }
}

func perform(_ obj: P1 & P2) {
    obj.action()
}

let d = Derived()
perform(d)
ADerived action
BRuntime error
CCompile-time error: ambiguous method
DBase action
Attempts:
2 left
💡 Hint
Consider method overriding and protocol composition.
❓ Predict Output
advanced
2:00remaining
Behavior of protocol composition with optional protocol requirements
What happens when this Swift code runs?
Swift
@objc protocol OptionalProtocol {
    @objc optional func optionalMethod()
}

class MyClass: OptionalProtocol {
}

func callOptional(_ obj: OptionalProtocol) {
    if let method = obj.optionalMethod {
        method()
    } else {
        print("No method implemented")
    }
}

let instance = MyClass()
callOptional(instance)
ANo method implemented
BRuntime error: optionalMethod not found
CCompile-time error: optional methods not supported
DEmpty output
Attempts:
2 left
💡 Hint
Think about how optional protocol methods behave when not implemented.
🧠 Conceptual
expert
2:00remaining
Understanding protocol composition type identity
Given the following Swift code, what is the type of the variable 'combined'?
Swift
protocol Alpha {
    func alphaMethod()
}

protocol Beta {
    func betaMethod()
}

struct S: Alpha, Beta {
    func alphaMethod() { print("Alpha") }
    func betaMethod() { print("Beta") }
}

let s = S()
let combined: Alpha & Beta = s
AA union type that can be either Alpha or Beta
BA tuple containing Alpha and Beta instances
CAn array of Alpha and Beta types
DA single type that conforms to both Alpha and Beta protocols
Attempts:
2 left
💡 Hint
Recall what protocol composition means in Swift type system.

Practice

(1/5)
1. What does protocol composition in Swift allow you to do?
easy
A. Combine multiple protocols into one requirement without creating a new protocol
B. Create a new class that inherits from multiple classes
C. Define a protocol with stored properties
D. Override methods in a protocol extension

Solution

  1. Step 1: Understand protocol composition concept

    Protocol composition uses the & operator to require multiple protocols at once without defining a new protocol.
  2. Step 2: Compare options with concept

    Only Combine multiple protocols into one requirement without creating a new protocol correctly describes combining multiple protocols without creating a new one. Other options describe unrelated or incorrect Swift features.
  3. Final Answer:

    Combine multiple protocols into one requirement without creating a new protocol -> Option A
  4. Quick Check:

    Protocol composition = Combine protocols [OK]
Hint: Remember & means combine protocols, not inherit classes [OK]
Common Mistakes:
  • Confusing protocol composition with class inheritance
  • Thinking protocols can have stored properties
  • Believing protocol extensions override methods
2. Which of the following is the correct syntax to declare a function parameter that requires both Codable and Equatable protocols using protocol composition?
easy
A. func save(item: Codable | Equatable) {}
B. func save(item: Codable & Equatable) {}
C. func save(item: Codable, Equatable) {}
D. func save(item: Codable && Equatable) {}

Solution

  1. Step 1: Recall protocol composition syntax

    Swift uses & to combine protocols in type requirements, like Codable & Equatable.
  2. Step 2: Evaluate each option

    func save(item: Codable & Equatable) {} uses correct & syntax. func save(item: Codable | Equatable) {} uses | which is invalid. func save(item: Codable, Equatable) {} uses comma which is invalid. func save(item: Codable && Equatable) {} uses && which is invalid.
  3. Final Answer:

    func save(item: Codable & Equatable) {} -> Option B
  4. Quick Check:

    Use & to combine protocols [OK]
Hint: Use & to combine protocols, not |, comma, or && [OK]
Common Mistakes:
  • Using | or && instead of & for protocol composition
  • Separating protocols with commas in parameter types
  • Confusing logical operators with protocol composition
3. What will be the output of the following Swift code?
protocol A { func foo() }
protocol B { func bar() }
struct MyStruct: A, B {
  func foo() { print("foo") }
  func bar() { print("bar") }
}
func callBoth(item: A & B) {
  item.foo()
  item.bar()
}
let obj = MyStruct()
callBoth(item: obj)
medium
A. foo\nbar
B. foo
C. bar
D. Compilation error

Solution

  1. Step 1: Understand protocol composition usage

    The function callBoth requires an argument conforming to both A and B. MyStruct conforms to both.
  2. Step 2: Trace function calls

    Inside callBoth, foo() prints "foo" and bar() prints "bar". Both are called in order.
  3. Final Answer:

    foo bar -> Option A
  4. Quick Check:

    Both protocol methods called = foo\nbar [OK]
Hint: Both protocols' methods run in order when composed [OK]
Common Mistakes:
  • Assuming only one protocol method runs
  • Expecting a compile error due to protocol composition
  • Confusing protocol conformance with inheritance
4. Identify the error in this Swift code using protocol composition:
protocol P1 { func p1Method() }
protocol P2 { func p2Method() }
func testFunc(param: P1 & P2) {
  param.p1Method()
  param.p2Method()
}
struct S: P1 {
  func p1Method() { print("P1") }
}
let s = S()
testFunc(param: s)
medium
A. Method p2Method is missing in testFunc
B. Function testFunc has wrong parameter syntax
C. Protocols P1 and P2 cannot be combined
D. Struct S does not conform to protocol P2

Solution

  1. Step 1: Check struct conformance

    Struct S conforms only to P1, missing P2 conformance.
  2. Step 2: Analyze function parameter requirement

    Function testFunc requires a parameter conforming to both P1 and P2. Passing s fails because s lacks P2.
  3. Final Answer:

    Struct S does not conform to protocol P2 -> Option D
  4. Quick Check:

    Missing protocol conformance causes error [OK]
Hint: Check all protocols are conformed before passing composed type [OK]
Common Mistakes:
  • Assuming partial protocol conformance is enough
  • Thinking function parameter syntax is incorrect
  • Believing protocols cannot be combined with &
5. Given these protocols and structs:
protocol Drawable { func draw() }
protocol Colorable { var color: String { get } }
struct Circle: Drawable, Colorable {
  var color: String
  func draw() { print("Drawing a circle") }
}
struct Square: Drawable {
  func draw() { print("Drawing a square") }
}

Which of the following function signatures correctly accepts only objects that are both Drawable and Colorable?
hard
A. func render(item: Drawable) { item.draw() }
B. func render(item: Drawable | Colorable) { item.draw() }
C. func render(item: Drawable & Colorable) { item.draw(); print(item.color) }
D. func render(item: Colorable) { print(item.color) }

Solution

  1. Step 1: Understand protocol composition for parameters

    To accept only objects conforming to both Drawable and Colorable, use Drawable & Colorable.
  2. Step 2: Check each function signature

    func render(item: Drawable & Colorable) { item.draw(); print(item.color) } uses correct composition and accesses both draw() and color. Options A, B, and D either use invalid syntax or accept only one protocol.
  3. Final Answer:

    func render(item: Drawable & Colorable) { item.draw(); print(item.color) } -> Option C
  4. Quick Check:

    Use & to require multiple protocols [OK]
Hint: Use & to require multiple protocols in parameters [OK]
Common Mistakes:
  • Using | instead of & for protocol composition
  • Accepting only one protocol when both are needed
  • Trying to access properties/methods not guaranteed by parameter type
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