Bird
Raised Fist0
Swiftprogramming~20 mins

Why protocol-oriented design matters in Swift - Challenge Your Understanding

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Protocol Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of protocol extension method call
What will be printed when this Swift code runs?
Swift
protocol Greetable {
    func greet()
}

extension Greetable {
    func greet() {
        print("Hello from protocol extension")
    }
}

struct Person: Greetable {
    func greet() {
        print("Hello from Person struct")
    }
}

let p: Greetable = Person()
p.greet()
AHello from protocol extension
BRuntime error: method not found
CCompilation error: greet() not implemented
DHello from Person struct
Attempts:
2 left
💡 Hint
Think about how protocol extensions provide default implementations and how method dispatch works with protocol-typed variables.
🧠 Conceptual
intermediate
1:30remaining
Why use protocols instead of base classes?
Which of the following is the main advantage of using protocols over base classes in Swift's protocol-oriented design?
AProtocols can be instantiated directly, classes cannot.
BProtocols can store properties with default values, classes cannot.
CProtocols allow multiple inheritance of behavior, while classes do not.
DProtocols enforce implementation of stored properties, classes do not.
Attempts:
2 left
💡 Hint
Think about how Swift handles inheritance and how protocols differ from classes.
🔧 Debug
advanced
2:30remaining
Fix the unexpected output in protocol extension
This Swift code prints "Hello from protocol extension" but the developer expects "Hello from Dog struct". What is the cause?
Swift
protocol Animal {
    func speak()
}

extension Animal {
    func speak() {
        print("Hello from protocol extension")
    }
}

struct Dog: Animal {
    func speak() {
        print("Hello from Dog struct")
    }
}

let pet: Animal = Dog()
pet.speak()
ADog struct does not implement speak(), so protocol extension is used.
BThe variable pet is typed as Animal, so protocol extension method is called due to static dispatch.
CThe speak() method in Dog is private, so protocol extension is called.
DThe protocol Animal requires a default implementation, so Dog's method is ignored.
Attempts:
2 left
💡 Hint
Consider how Swift decides which method to call when using protocol-typed variables.
📝 Syntax
advanced
1:30remaining
Identify the syntax error in protocol conformance
Which option contains the correct syntax to make a struct conform to a protocol with a method requirement?
Swift
protocol Runner {
    func run()
}

struct Athlete {
    // Conformance here
}
A
struct Athlete: Runner {
    func run() {
        print("Running")
    }
}
B
struct Athlete implements Runner {
    func run() {
        print("Running")
    }
}
C
struct Athlete extends Runner {
    func run() {
        print("Running")
    }
}
D
struct Athlete conforms Runner {
    func run() {
        print("Running")
    }
}
Attempts:
2 left
💡 Hint
Remember the Swift keyword to declare protocol conformance.
🚀 Application
expert
3:00remaining
Determine the number of methods available via protocol composition
Given the protocols and struct below, how many unique methods can be called on the variable 'obj' typed as 'A & B'?
Swift
protocol A {
    func methodA()
}

protocol B {
    func methodB()
    func methodC()
}

struct C: A, B {
    func methodA() { print("A") }
    func methodB() { print("B") }
    func methodC() { print("C") }
    func methodD() { print("D") }
}

let obj: A & B = C()
A3
B4
C2
D1
Attempts:
2 left
💡 Hint
Count only the methods declared in the protocols A and B accessible via the protocol composition type.

Practice

(1/5)
1. What is the main benefit of using protocols in Swift's protocol-oriented design?
easy
A. They make the code run faster.
B. They store data like variables.
C. They replace classes completely.
D. They allow different types to share common behavior.

Solution

  1. Step 1: Understand what protocols do

    Protocols define a set of behaviors that many types can adopt and share.
  2. Step 2: Identify the main benefit

    This sharing of behavior helps make code reusable and flexible.
  3. Final Answer:

    They allow different types to share common behavior. -> Option D
  4. Quick Check:

    Protocols = shared behavior [OK]
Hint: Protocols share behavior across types, not data storage [OK]
Common Mistakes:
  • Thinking protocols speed up code execution
  • Confusing protocols with classes
  • Believing protocols store data
2. Which of the following is the correct way to declare a protocol in Swift?
easy
A. struct Vehicle: protocol { func drive() }
B. class Vehicle { func drive() }
C. protocol Vehicle { func drive() }
D. func protocol Vehicle() { drive() }

Solution

  1. Step 1: Recall Swift protocol syntax

    Protocols are declared using the keyword 'protocol' followed by the name and curly braces.
  2. Step 2: Match the correct syntax

    protocol Vehicle { func drive() } correctly uses 'protocol Vehicle { func drive() }'. Other options misuse keywords or structure.
  3. Final Answer:

    protocol Vehicle { func drive() } -> Option C
  4. Quick Check:

    Protocol declaration = protocol keyword + name + braces [OK]
Hint: Protocols start with 'protocol' keyword, not 'class' or 'func' [OK]
Common Mistakes:
  • Using 'class' instead of 'protocol'
  • Trying to inherit protocol with ':' in struct incorrectly
  • Writing 'func protocol' which is invalid
3. Consider this Swift code:
protocol Greetable { func greet() -> String }

struct Person: Greetable {
  func greet() -> String { "Hello!" }
}

let p = Person()
print(p.greet())

What will be the output?
medium
A. Hello!
B. greet()
C. Error: Missing function implementation
D. nil

Solution

  1. Step 1: Check protocol conformance

    Person struct implements the greet() method required by Greetable.
  2. Step 2: Understand the print output

    Calling p.greet() returns "Hello!", which is printed.
  3. Final Answer:

    Hello! -> Option A
  4. Quick Check:

    Implemented method returns "Hello!" [OK]
Hint: Implemented protocol methods run normally when called [OK]
Common Mistakes:
  • Assuming protocol methods print their name
  • Expecting runtime error without implementation
  • Thinking print outputs nil if no return
4. What is wrong with this Swift code?
protocol Drawable {
  func draw()
}

struct Circle: Drawable {
  // Missing draw() implementation
}

let c = Circle()
medium
A. Circle must implement draw() or code won't compile.
B. Circle can omit draw() because it's a struct.
C. Protocol Drawable should not have functions.
D. Circle should be a class, not a struct.

Solution

  1. Step 1: Check protocol requirements

    Drawable requires any conforming type to implement draw().
  2. Step 2: Verify Circle implementation

    Circle does not implement draw(), so it violates the protocol.
  3. Final Answer:

    Circle must implement draw() or code won't compile. -> Option A
  4. Quick Check:

    Protocol methods must be implemented [OK]
Hint: All protocol methods must be implemented to compile [OK]
Common Mistakes:
  • Thinking structs can skip protocol methods
  • Believing protocols can't have functions
  • Confusing struct vs class requirements
5. You want to design a system where multiple types like Car and Bicycle can be "startable" with a start() method. Using protocol-oriented design, which approach is best?
hard
A. Write separate start() functions outside the types for each vehicle.
B. Create a protocol Startable with start() and have both types conform to it.
C. Make Car and Bicycle subclasses of a common class with start() method.
D. Use global variables to track if Car or Bicycle started.

Solution

  1. Step 1: Identify shared behavior

    Both Car and Bicycle need a start() method, which is shared behavior.
  2. Step 2: Apply protocol-oriented design

    Defining a Startable protocol with start() and making both types conform promotes reuse and flexibility.
  3. Step 3: Compare other options

    Subclassing limits flexibility; separate functions or globals reduce clarity and reuse.
  4. Final Answer:

    Create a protocol Startable with start() and have both types conform to it. -> Option B
  5. Quick Check:

    Protocol for shared behavior = best design [OK]
Hint: Use protocols to share behavior across unrelated types [OK]
Common Mistakes:
  • Using class inheritance when unrelated types
  • Writing separate functions instead of protocol
  • Using global state instead of behavior abstraction
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