2. Which of the following is the correct syntax to declare conditional conformance for a generic struct Box to the protocol Equatable when its generic type T is Equatable?
easy
A. struct Box<T>: Equatable where T: Equatable {}
B. struct Box<T> where T: Equatable: Equatable {}
C. struct Box<T>: Equatable if T: Equatable {}
D. struct Box<T>: Equatable where T == Equatable {}
Solution
Step 1: Recall Swift conditional conformance syntax
Use where clause after the protocol conformance list to specify conditions.
Step 2: Match syntax to options
struct Box<T>: Equatable where T: Equatable {} correctly places where T: Equatable after : Equatable. Others misuse syntax keywords or order.
Final Answer:
struct Box<T>: Equatable where T: Equatable {} -> Option A
Quick Check:
Correct syntax uses 'where' after protocol list [OK]
C. Extension syntax is invalid; 'where' clause misplaced
D. Cannot conform to Hashable with only T: Equatable; T must be Hashable
Solution
Step 1: Understand Hashable requirements
To conform to Hashable, all stored properties must be Hashable. Here, T must conform to Hashable, not just Equatable.
Step 2: Check the constraint in the code
The code requires T: Equatable, which is insufficient for Hashable conformance.
Final Answer:
Cannot conform to Hashable with only T: Equatable; T must be Hashable -> Option D
Quick Check:
Hashable requires T: Hashable, not just Equatable [OK]
Hint: Hashable needs Hashable constraint, not just Equatable [OK]
Common Mistakes:
Confusing Equatable with Hashable requirements
Thinking 'hash(into:)' must be static
Misplacing 'where' clause in extension
5. You want to make a generic struct Pair conform to Codable only if both generic types A and B conform to Codable. Which of the following is the correct way to declare this conditional conformance?
hard
A. extension Pair: Codable if A: Codable and B: Codable {}
B. extension Pair: Codable where A & B: Codable {}
C. extension Pair: Codable where A: Codable, B: Codable {}
D. extension Pair: Codable where A == Codable, B == Codable {}
Solution
Step 1: Understand multiple constraints in 'where' clause
Swift allows multiple constraints separated by commas in the where clause.
Step 2: Match correct syntax
extension Pair: Codable where A: Codable, B: Codable {} correctly uses where A: Codable, B: Codable. Others use invalid syntax like '&', 'if', or '==' for constraints.
Final Answer:
extension Pair: Codable where A: Codable, B: Codable {} -> Option C
Quick Check:
Multiple constraints separated by commas in 'where' [OK]
Hint: Use commas to separate multiple 'where' constraints [OK]
Common Mistakes:
Using '&' instead of comma in where clause
Using 'if' instead of 'where'
Using '==' instead of ':' for constraints
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.