An extension with constraints adds new functionality to a type only when certain conditions are met, like when the type conforms to a specific protocol or has a certain associated type.
Click to reveal answer
beginner
How do you write an extension with a constraint that applies only to arrays of Equatable elements?
You write: extension Array where Element: Equatable { /* new methods here */ }
Click to reveal answer
intermediate
Why use extensions with constraints instead of regular extensions?
Because they let you add features only when the type meets specific requirements, keeping your code safe and relevant to the type's abilities.
Click to reveal answer
intermediate
Can you extend a generic type with constraints on its associated types?
Yes, you can add constraints on associated types in extensions to provide functionality only when those associated types meet certain conditions.
Click to reveal answer
intermediate
Example: What does this extension do? <code>extension Collection where Element: Comparable { func isSorted() -> Bool { for i in 1..<count { if self[self.index(startIndex, offsetBy: i)] < self[self.index(startIndex, offsetBy: i - 1)] { return false } } return true } }</code>
It adds a method isSorted() to any collection whose elements can be compared. This method checks if the collection's elements are in ascending order.
Click to reveal answer
What does the 'where' keyword do in a Swift extension with constraints?
ASpecifies conditions that the type must meet for the extension to apply
BDefines a new type inside the extension
CImports external libraries
DDeclares a variable
✗ Incorrect
The 'where' keyword sets conditions that limit when the extension's code applies, based on the type's properties or protocols.
Which of these is a valid constraint in a Swift extension?
Aextension Array with Element: Comparable {}
Bextension Array if Element == Int {}
Cextension Array where Element: Hashable {}
Dextension Array when Element: Equatable {}
✗ Incorrect
The correct syntax uses 'where' to specify constraints, like 'where Element: Hashable'.
Can you add a method in an extension that only works if the type conforms to a protocol?
ANo, extensions cannot have conditions
BOnly if the method is static
COnly if the type is a class
DYes, by using an extension with constraints
✗ Incorrect
Extensions with constraints allow adding methods only when the type meets protocol conformance.
What happens if you try to use a constrained extension on a type that does not meet the constraint?
AThe extension's methods are not available for that type
BThe program crashes at runtime
CThe extension applies anyway
DThe compiler ignores the type
✗ Incorrect
The extension's methods only exist for types that satisfy the constraints; otherwise, they are unavailable.
Which of these is NOT a valid use of constraints in extensions?
Aextension Dictionary where Key: Hashable {}
Bextension String where Element == Character {}
Cextension Equatable where Self: Comparable {}
Dextension Array where Element: Numeric {}
✗ Incorrect
String does not have an 'Element' type alias accessible this way; the syntax is invalid for String.
Explain how extensions with constraints help keep Swift code safe and organized.
Think about when and why you want to add features only to certain types.
You got /4 concepts.
Write a simple Swift extension with a constraint that adds a method only to arrays of integers.
Use 'extension Array where Element == Int' and add a method like sum()
You got /5 concepts.
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
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.
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.
Final Answer:
To add functionality only to types that meet specific conditions -> Option C
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
Step 1: Recall correct syntax for constrained extensions
Swift uses where followed by the condition, e.g., Element: Equatable to constrain extensions.
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.
Final Answer:
extension Array where Element: Equatable { } -> Option D
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
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.
Step 2: Calculate the sum of the array
The sum() method uses reduce(0, +) which adds all elements: 1+2+3+4 = 10.
Final Answer:
10 -> Option B
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
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.
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.
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.
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.
Final Answer:
reduce(1, *) is invalid syntax -> Option A
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
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.
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..
Final Answer:
Option A correctly implements isAllEqual() with proper constraint and safe code -> Option A
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 unknownstrongwhile earning +1 Grip toward your certificate.