Bird
Raised Fist0
Swiftprogramming~20 mins

Extensions with constraints in Swift - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Swift Extensions Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of extension with protocol constraint

What is the output of this Swift code?

Swift
protocol Describable {
    func describe() -> String
}

struct Item: Describable {
    var name: String
    func describe() -> String {
        return "Item: \(name)"
    }
}

extension Array where Element: Describable {
    func allDescriptions() -> [String] {
        self.map { $0.describe() }
    }
}

let items = [Item(name: "Pen"), Item(name: "Book")]
print(items.allDescriptions())
ACompilation error: 'describe()' not found
B["Pen", "Book"]
C["Item: Pen", "Item: Book"]
DRuntime error: Cannot convert value
Attempts:
2 left
💡 Hint

Check how the extension applies only when Element conforms to Describable.

❓ Predict Output
intermediate
2:00remaining
Extension with class constraint output

What will this Swift code print?

Swift
class Vehicle {
    var wheels: Int
    init(wheels: Int) {
        self.wheels = wheels
    }
}

class Car: Vehicle {}

extension Array where Element: Vehicle {
    func totalWheels() -> Int {
        self.reduce(0) { $0 + $1.wheels }
    }
}

let vehicles: [Vehicle] = [Car(wheels: 4), Vehicle(wheels: 2)]
print(vehicles.totalWheels())
ACompilation error: Cannot extend Array with class constraint
B6
CRuntime error: Method not found
D4
Attempts:
2 left
💡 Hint

Remember the extension applies to arrays of Vehicle or subclasses.

🔧 Debug
advanced
2:00remaining
Why does this extension not compile?

Why does this Swift extension cause a compilation error?

Swift
extension Array where Element: Equatable & Comparable {
    func isSortedAndUnique() -> Bool {
        for i in 1..<self.count {
            if self[i] <= self[i-1] {
                return false
            }
        }
        return true
    }
}
ASwift does not allow multiple protocol constraints with '&' in extensions
BThe syntax for multiple constraints should use a where clause with commas, not '&'
CThe extension requires Element to be a class, but protocols are used
DThe operator '<=' is not defined for Element
Attempts:
2 left
💡 Hint

Check if the operator used is guaranteed by the protocols.

📝 Syntax
advanced
2:00remaining
Correct syntax for extension with generic constraint

Which option shows the correct syntax to extend Array only when its elements conform to Hashable?

Aextension Array where Element: Hashable {}
Bextension Array where Element == Hashable {}
Cextension Array<Element> where Element: Hashable {}
Dextension Array<Element: Hashable> {}
Attempts:
2 left
💡 Hint

Remember the syntax for constrained extensions uses 'where'.

🚀 Application
expert
3:00remaining
Implement extension with multiple constraints

Given the following code, which option correctly implements an extension on Array where Element is both Numeric and Comparable, adding a method maxValue() that returns the maximum element?

Swift
extension Array where Element: Numeric & Comparable {
    func maxValue() -> Element? {
        guard var maxElem = self.first else { return nil }
        for elem in self {
            if elem > maxElem {
                maxElem = elem
            }
        }
        return maxElem
    }
}
A
extension Array where Element: Numeric &amp; Comparable {
    func maxValue() -&gt; Element? {
        self.max()
    }
}
B
extension Array where Element: Numeric, Comparable {
    func maxValue() -&gt; Element? {
        self.max()
    }
}
C
extension Array&lt;Element&gt; where Element: Numeric &amp; Comparable {
    func maxValue() -&gt; Element? {
        self.max()
    }
}
D
extension Array where Element == Numeric &amp; Comparable {
    func maxValue() -&gt; Element? {
        self.max()
    }
}
Attempts:
2 left
💡 Hint

Check the correct syntax for multiple protocol constraints in extensions.

Practice

(1/5)
1. What is the main purpose of using where in Swift extensions with constraints?
easy
A. To override existing methods in a class
B. To create a new class from an existing one
C. To add functionality only to types that meet specific conditions
D. To declare a variable inside an extension

Solution

  1. Step 1: Understand the role of where in extensions

    The where keyword is used to specify conditions that types must meet to gain the added functionality.
  2. Step 2: Recognize the purpose of constraints

    Constraints ensure that only types matching the condition get the new methods or properties, keeping code safe and organized.
  3. Final Answer:

    To add functionality only to types that meet specific conditions -> Option C
  4. Quick Check:

    Extensions with where add features conditionally = A [OK]
Hint: Remember: where limits extension to certain types [OK]
Common Mistakes:
  • Thinking where creates new classes
  • Confusing extensions with inheritance
  • Using where to declare variables
2. Which of the following is the correct syntax to extend Array only when its elements conform to the Equatable protocol?
easy
A. extension Array where Element == Equatable { }
B. extension Array if Element == Equatable { }
C. extension Array with Element: Equatable { }
D. extension Array where Element: Equatable { }

Solution

  1. Step 1: Recall correct syntax for constrained extensions

    Swift uses where followed by the condition, e.g., Element: Equatable to constrain extensions.
  2. Step 2: Identify the correct option

    extension Array where Element: Equatable { } uses the correct syntax: extension Array where Element: Equatable { }. Others misuse if, ==, or with.
  3. Final Answer:

    extension Array where Element: Equatable { } -> Option D
  4. Quick Check:

    Use where and colon for protocol conformance = C [OK]
Hint: Use where Type: Protocol for constraints [OK]
Common Mistakes:
  • Using == instead of : for protocol conformance
  • Replacing where with if
  • Writing with instead of where
3. What will be the output of this Swift code?
extension Collection where Element: Numeric {
    func sum() -> Element {
        reduce(0, +)
    }
}

let numbers = [1, 2, 3, 4]
print(numbers.sum())
medium
A. 0
B. 10
C. Error: sum() not found
D. 1234

Solution

  1. Step 1: Understand the extension constraint

    The extension adds a sum() method only to collections whose elements conform to Numeric. Array of Int fits this.
  2. Step 2: Calculate the sum of the array

    The sum() method uses reduce(0, +) which adds all elements: 1+2+3+4 = 10.
  3. Final Answer:

    10 -> Option B
  4. Quick Check:

    Sum of [1,2,3,4] = 10 [OK]
Hint: Check if element type matches constraint to use extension methods [OK]
Common Mistakes:
  • Assuming sum() works on non-Numeric elements
  • Thinking sum() concatenates numbers
  • Ignoring the extension constraint
4. Identify the error in this Swift extension:
extension Array where Element == Int {
    func multiplyAll() -> Int {
        reduce(1, *)
    }
}
medium
A. reduce(1, *) is invalid syntax
B. Cannot use == to check type equality in extension constraints
C. Missing return keyword in multiplyAll()
D. Array cannot be extended with constraints

Solution

  1. Step 1: Check extension constraint syntax

    Swift requires Element: SomeProtocol or Element == SomeType is valid only for type equality, but for generic parameters, Element == Int is allowed.
  2. Step 2: Verify if Element == Int is valid here

    Actually, Element == Int is valid syntax for type equality constraints in extensions, so Cannot use == to check type equality in extension constraints is incorrect.
  3. Step 3: Check other options

    Missing return keyword in multiplyAll(): The function uses implicit return allowed in single-expression functions, so no error.
    reduce(1, *) is invalid syntax: reduce(1, *) is invalid syntax because the operator * cannot be passed as a bare argument like that.
    Array cannot be extended with constraints: Arrays can be extended with constraints.
  4. Step 4: Re-examine Cannot use == to check type equality in extension constraints

    In Swift 5+, Element == Int is valid. So no syntax error here.
  5. Final Answer:

    reduce(1, *) is invalid syntax -> Option A
  6. Quick Check:

    Operator * must be passed as a closure or function, not bare = B [OK]
Hint: Remember: Element == Type is valid for type equality [OK]
Common Mistakes:
  • Thinking == is invalid in extension constraints
  • Expecting explicit return in single-expression functions
  • Misreading reduce syntax
5. You want to add a method isAllEqual() to arrays only when their elements conform to Equatable. Which extension correctly implements this method to return true if all elements are equal, or false otherwise?
hard
A. extension Array where Element: Equatable { func isAllEqual() -> Bool { guard let first = self.first else { return true } return allSatisfy { $0 == first } } }
B. extension Array where Element == Equatable { func isAllEqual() -> Bool { for i in 1..
C. extension Array where Element: Equatable { func isAllEqual() -> Bool { for element in self { if element != self[0] { return false } } return true } }
D. extension Array { func isAllEqual() -> Bool { for i in 1..

Solution

  1. Step 1: Check the extension constraint correctness

    Only options A and C use where Element: Equatable, which is correct to add methods requiring equality checks.
  2. Step 2: Analyze method implementation

    extension Array where Element: Equatable { func isAllEqual() -> Bool { guard let first = self.first else { return true } return allSatisfy { $0 == first } } } safely handles empty arrays by returning true and uses allSatisfy for clarity.
    extension Array where Element: Equatable { func isAllEqual() -> Bool { for element in self { if element != self[0] { return false } } return true } } compares each element to self[0] but does not handle empty arrays, which can cause runtime error.
    extension Array where Element == Equatable { func isAllEqual() -> Bool { for i in 1..Element == Equatable which is invalid syntax.
    extension Array { func isAllEqual() -> Bool { for i in 1..
  3. Final Answer:

    Option A correctly implements isAllEqual() with proper constraint and safe code -> Option A
  4. Quick Check:

    Use where Element: Equatable and safe checks = A [OK]
Hint: Use where Element: Equatable and safe first element check [OK]
Common Mistakes:
  • Using Element == Equatable instead of Element: Equatable
  • Not handling empty arrays safely
  • Extending without constraints for Equatable methods
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