Bird
Raised Fist0
Swiftprogramming~20 mins

Protocol extensions with default implementations in Swift - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Protocol Extension Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of protocol extension default method call
What is the output of this Swift code when calling greet() on person?
Swift
protocol Greeter {
    func greet()
}

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

struct Person: Greeter {}

let person = Person()
person.greet()
AHello from protocol extension
BCompile-time error: Missing implementation of greet()
CRuntime error: Method greet() not found
DNo output
Attempts:
2 left
💡 Hint
Protocol extensions provide default implementations if the conforming type does not implement the method.
❓ Predict Output
intermediate
2:00remaining
Overriding default implementation in protocol extension
What will be printed when greet() is called on dog?
Swift
protocol Greeter {
    func greet()
}

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

struct Dog: Greeter {
    func greet() {
        print("Woof! Hello from Dog")
    }
}

let dog = Dog()
dog.greet()
AHello from protocol extension
BCompile-time error: Duplicate method implementation
CWoof! Hello from Dog
DNo output
Attempts:
2 left
💡 Hint
If the conforming type implements the method, it overrides the default from the extension.
🔧 Debug
advanced
3:00remaining
Why does this code print the protocol extension method instead of the struct's method?
Given the code below, why does calling greeter.greet() print "Hello from protocol extension" instead of "Hi from Cat"?
Swift
protocol Greeter {
}

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

struct Cat: Greeter {
    func greet() {
        print("Hi from Cat")
    }
}

let cat = Cat()
let greeter: Greeter = cat
greeter.greet()
ABecause Cat does not implement greet(), the default method is called.
BBecause the method is called on a protocol-typed variable, the protocol extension method is used instead of the struct's method.
CBecause greet() is a static method, the protocol extension method is always called.
DBecause the protocol requires @objc, the method dispatch fails to call Cat's method.
Attempts:
2 left
💡 Hint
Consider how Swift dispatches methods when called on protocol-typed variables.
📝 Syntax
advanced
2:00remaining
Which option correctly adds a default implementation to a protocol method with parameters?
Given the protocol below, which option correctly provides a default implementation for describe(age:) in a protocol extension?
Swift
protocol Describable {
    func describe(age: Int)
}
A
extension Describable {
    func describe(age: Int) {
        print("Age is \(age)")
    }
}
B
extension Describable {
    func describe() {
        print("Age is unknown")
    }
}
C
extension Describable {
    func describe(age) {
        print("Age is \(age)")
    }
}
D
extension Describable {
    func describe(age: String) {
        print("Age is \(age)")
    }
}
Attempts:
2 left
💡 Hint
The method signature in the extension must exactly match the protocol's method signature.
🚀 Application
expert
3:00remaining
Using protocol extensions to add default behavior with constraints
Consider the protocol Summable below. Which option correctly uses a protocol extension with a constraint to provide a default implementation of sum() only for arrays of Int?
Swift
protocol Summable {
    associatedtype Element
    func sum() -> Element
}
A
extension Summable {
    func sum() -> Element {
        return 0
    }
}
B
extension Summable where Element == Int {
    func sum() -> Int {
        return self.reduce(0, +)
    }
}
C
extension Summable where Element: Numeric {
    func sum() -> Element {
        return (self as! [Element]).reduce(0, +)
    }
}
D
extension Summable where Element == Int {
    func sum() -> Int {
        return (self as! [Int]).reduce(0, +)
    }
}
Attempts:
2 left
💡 Hint
You must constrain the extension to Element == Int and cast self to [Int] to use reduce.

Practice

(1/5)
1. What is the main purpose of using protocol extensions with default implementations in Swift?
easy
A. To allow protocols to store properties
B. To create new classes that inherit from protocols
C. To enforce that all conforming types must implement every method
D. To provide default method implementations that all conforming types can use

Solution

  1. Step 1: Understand protocol extensions

    Protocol extensions allow adding methods or properties with default behavior to protocols.
  2. Step 2: Identify the purpose of default implementations

    Default implementations let conforming types use common code without writing it themselves.
  3. Final Answer:

    To provide default method implementations that all conforming types can use -> Option D
  4. Quick Check:

    Default implementations = shared code for all [OK]
Hint: Default implementations give shared code to all conforming types [OK]
Common Mistakes:
  • Thinking protocols can store properties
  • Confusing protocol inheritance with extensions
  • Believing all methods must be implemented manually
2. Which of the following is the correct syntax to add a default implementation for a protocol method in Swift?
easy
A. extension MyProtocol { func greet() { print(\"Hello\") } }
B. protocol MyProtocol { extension func greet() { print(\"Hello\") } }
C. func greet() in MyProtocol { print(\"Hello\") }
D. MyProtocol { func greet() { print(\"Hello\") } }"

Solution

  1. Step 1: Recall syntax for protocol extensions

    Default implementations are added inside an extension of the protocol.
  2. Step 2: Check each option

    extension MyProtocol { func greet() { print(\"Hello\") } } correctly uses extension MyProtocol { func greet() { ... } }. Others misuse keywords or structure.
  3. Final Answer:

    extension MyProtocol { func greet() { print("Hello") } } -> Option A
  4. Quick Check:

    Use extension to add defaults [OK]
Hint: Use 'extension ProtocolName' to add default methods [OK]
Common Mistakes:
  • Trying to put method bodies inside protocol declaration
  • Using 'extension' inside protocol block
  • Omitting the 'extension' keyword
3. Consider the code below:
protocol Speaker {
    func speak()
}

extension Speaker {
    func speak() {
        print("Speaking from extension")
    }
}

struct Person: Speaker {
    func speak() {
        print("Person speaking")
    }
}

struct Robot: Speaker {}

let p = Person()
p.speak()

let r = Robot()
r.speak()

What is the output when this code runs?
medium
A. Person speaking Robot speaking
B. Speaking from extension Speaking from extension
C. Person speaking Speaking from extension
D. Compilation error

Solution

  1. Step 1: Understand method resolution for protocol extensions

    If a conforming type provides its own method, it overrides the default from the extension.
  2. Step 2: Analyze the structs

    Person implements speak() so it prints "Person speaking". Robot does not implement it, so uses default "Speaking from extension".
  3. Final Answer:

    Person speaking Speaking from extension -> Option C
  4. Quick Check:

    Own method overrides default extension [OK]
Hint: Own method overrides default extension method [OK]
Common Mistakes:
  • Assuming default is always called
  • Expecting Robot to cause error
  • Confusing protocol declaration with implementation
4. The following code tries to add a default implementation for describe() in a protocol extension, but it causes a compile error. What is the mistake?
protocol Describable {
    func describe()
}

extension Describable {
    func describe
    {
        print("Default description")
    }
}
medium
A. Protocol cannot have methods without bodies
B. Missing parentheses after method name in extension
C. Extension cannot provide method implementations
D. Missing 'func' keyword in extension

Solution

  1. Step 1: Check method syntax in extension

    Method definitions require parentheses even if no parameters are present.
  2. Step 2: Identify the error

    The extension method func describe is missing parentheses () after the name.
  3. Final Answer:

    Missing parentheses after method name in extension -> Option B
  4. Quick Check:

    Method syntax needs () even if empty [OK]
Hint: Always include () after method name in definitions [OK]
Common Mistakes:
  • Omitting parentheses in method declaration
  • Thinking protocol methods must have bodies
  • Believing extensions can't implement methods
5. You want to create a protocol Identifiable with a property id and a default method identify() that prints the id. How would you write the protocol and extension so that conforming types can use the default identify() without extra code?
hard
A. protocol Identifiable { var id: String { get } }\nextension Identifiable { func identify() { print(\"ID: \(id)\") } }
B. protocol Identifiable { func identify() }\nextension Identifiable { var id: String { return \"default\" } }
C. protocol Identifiable { var id: String }\nextension Identifiable { func identify() { print(id) } }
D. protocol Identifiable { var id: String { get set } }\nextension Identifiable { func identify() { print(\"ID: \(id)\") } }"

Solution

  1. Step 1: Define protocol with read-only property

    Use var id: String { get } to require an id property that conforming types must provide.
  2. Step 2: Provide default identify() method in extension

    Extension adds identify() that prints the id using string interpolation.
  3. Final Answer:

    protocol Identifiable { var id: String { get } }\nextension Identifiable { func identify() { print("ID: \(id)") } } -> Option A
  4. Quick Check:

    Protocol requires id; extension adds identify() [OK]
Hint: Require property with { get } and add method in extension [OK]
Common Mistakes:
  • Using var id: String without { get } or { get set }
  • Trying to provide stored properties in protocol extension
  • Defining identify() in protocol but not implementing in extension
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