0
0
Swiftprogramming~20 mins

Where clauses for complex constraints in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Swift Where Clause Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
ARuntime error
BImpossible
CValue is 5
DCompilation error due to where clause
Attempts:
2 left
💡 Hint
Think about the comparison and the where clause constraints.
🧠 Conceptual
intermediate
1:30remaining
Purpose of where clauses in Swift generics
What is the main purpose of using a where clause in Swift generic declarations?
ATo add constraints on generic types for more specific behavior
BTo declare variables inside a generic function
CTo create a new type alias
DTo handle errors in generic functions
Attempts:
2 left
💡 Hint
Think about how generics can be limited to certain types.
🔧 Debug
advanced
2: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")
AType mismatch error at call site
BRuntime crash due to invalid cast
CCompilation error: missing protocol conformance
DNo error, prints "a is less"
Attempts:
2 left
💡 Hint
Check the types passed to the function and the where clause.
📝 Syntax
advanced
1: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
}
AT: Equatable, T: Hashable
BT: Equatable & Hashable
CT: Equatable, Hashable
DT: Equatable && Hashable
Attempts:
2 left
💡 Hint
Swift uses a specific symbol to combine protocol constraints in where clauses.
🚀 Application
expert
3: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()
ACompilation error: missing example() implementation
BNo output
CRuntime error
DNumeric Item
Attempts:
2 left
💡 Hint
Check the protocol extension and the associated type constraint.