Challenge - 5 Problems
Swift Where Clause Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of generic function with where clause
What is the output of this Swift code using a generic function with a where clause?
Swift
func describe<T>(value: T) where T: CustomStringConvertible, T: Comparable { if value > value { print("Impossible") } else { print("Value is \(value)") } } describe(value: 5)
Attempts:
2 left
💡 Hint
Think about the comparison and the where clause constraints.
✗ Incorrect
The function requires T to conform to CustomStringConvertible and Comparable. The comparison value > value is always false, so the else branch runs, printing "Value is 5".
🧠 Conceptual
intermediate1:30remaining
Purpose of where clauses in Swift generics
What is the main purpose of using a where clause in Swift generic declarations?
Attempts:
2 left
💡 Hint
Think about how generics can be limited to certain types.
✗ Incorrect
Where clauses allow you to specify conditions on generic types, such as conforming to protocols or matching types, enabling more precise and safe code.
🔧 Debug
advanced2:30remaining
Identify the error in this generic function with where clause
What error does this Swift code produce?
Swift
func compare<T, U>(a: T, b: U) where T == U, T: Comparable { if a < b { print("a is less") } else { print("a is not less") } } compare(a: 3, b: "3")
Attempts:
2 left
💡 Hint
Check the types passed to the function and the where clause.
✗ Incorrect
The where clause requires T and U to be the same type, but the call passes Int and String, causing a type mismatch error at compile time.
📝 Syntax
advanced1:30remaining
Correct syntax for where clause with multiple constraints
Which option shows the correct syntax for a generic function with multiple where clause constraints?
Swift
func process<T>(item: T) where ... { // implementation }
Attempts:
2 left
💡 Hint
Swift uses a specific symbol to combine protocol constraints in where clauses.
✗ Incorrect
The correct syntax uses & to combine multiple protocol constraints in a where clause: where T: Equatable & Hashable.
🚀 Application
expert3:00remaining
Using where clause to restrict protocol extension
Given this protocol and extension, what will be the output of calling example() on an instance of MyStruct?
Swift
protocol ExampleProtocol { associatedtype Item func example() } extension ExampleProtocol where Item: Numeric { func example() { print("Numeric Item") } } struct MyStruct: ExampleProtocol { typealias Item = Int } let instance = MyStruct() instance.example()
Attempts:
2 left
💡 Hint
Check the protocol extension and the associated type constraint.
✗ Incorrect
The extension provides a default implementation of example() only when Item conforms to Numeric. Since MyStruct's Item is Int (which is Numeric), the extension method is used, printing "Numeric Item".