Bird
Raised Fist0
Swiftprogramming~20 mins

Conditional conformance in Swift - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Swift Conditional Conformance Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of conditional conformance with Equatable
What is the output of this Swift code using conditional conformance for Equatable?
Swift
struct Box<T> {
    let value: T
}
extension Box: Equatable where T: Equatable {
    static func == (lhs: Box<T>, rhs: Box<T>) -> Bool {
        return lhs.value == rhs.value
    }
}

let box1 = Box(value: 5)
let box2 = Box(value: 5)
let box3 = Box(value: 10)

print(box1 == box2)
print(box1 == box3)
Afalse\nfalse
Btrue\nfalse
Ctrue\ntrue
DCompilation error
Attempts:
2 left
💡 Hint
Think about how conditional conformance allows Box to be Equatable only if T is Equatable.
❓ Predict Output
intermediate
2:00remaining
Output of conditional conformance with CustomStringConvertible
What will this Swift code print when using conditional conformance for CustomStringConvertible?
Swift
struct Wrapper<T> {
    let item: T
}
extension Wrapper: CustomStringConvertible where T: CustomStringConvertible {
    var description: String {
        return "Wrapper contains: \(item.description)"
    }
}

struct Person: CustomStringConvertible {
    let name: String
    var description: String { name }
}

let p = Person(name: "Alice")
let w = Wrapper(item: p)
print(w.description)
AWrapper contains: Alice
BWrapper contains: Person
CCompilation error
DWrapper contains: Optional("Alice")
Attempts:
2 left
💡 Hint
Check how the description property is used in the extension.
❓ Predict Output
advanced
2:00remaining
Output of conditional conformance with Codable
What is the output of this Swift code that uses conditional conformance for Codable?
Swift
struct Container<T> {
    let content: T
}
extension Container: Codable where T: Codable {}

struct Item: Codable {
    let id: Int
    let name: String
}

let item = Item(id: 1, name: "Book")
let container = Container(content: item)

let encoder = JSONEncoder()
if let jsonData = try? encoder.encode(container),
   let jsonString = String(data: jsonData, encoding: .utf8) {
    print(jsonString)
} else {
    print("Encoding failed")
}
AEncoding failed
B{"id":1,"name":"Book"}
C{"content":{"id":1,"name":"Book"}}
DCompilation error
Attempts:
2 left
💡 Hint
Look at how Container encodes its content property.
❓ Predict Output
advanced
2:00remaining
Output of conditional conformance with Sequence and Collection
What will this Swift code print when using conditional conformance for Collection?
Swift
struct MyArray<T> {
    var elements: [T]
}
extension MyArray: Collection where T: Equatable {
    typealias Index = Int
    var startIndex: Int { elements.startIndex }
    var endIndex: Int { elements.endIndex }
    subscript(position: Int) -> T { elements[position] }
    func index(after i: Int) -> Int { elements.index(after: i) }
}

let arr = MyArray(elements: [1, 2, 3])
print(arr.contains(2))
Atrue
BRuntime error
CCompilation error
Dfalse
Attempts:
2 left
💡 Hint
Check how Collection conformance enables contains method.
❓ Predict Output
expert
3:00remaining
Output of nested conditional conformance with Optional and Equatable
What is the output of this Swift code using nested conditional conformance with Optional and Equatable?
Swift
extension Optional: Equatable where Wrapped: Equatable {
    public static func == (lhs: Optional<Wrapped>, rhs: Optional<Wrapped>) -> Bool {
        switch (lhs, rhs) {
        case (.some(let l), .some(let r)):
            return l == r
        case (.none, .none):
            return true
        default:
            return false
        }
    }
}

let a: Int? = 5
let b: Int? = 5
let c: Int? = nil

print(a == b)
print(a == c)
print(c == nil)
ACompilation error
Bfalse\nfalse\nfalse
Ctrue\ntrue\nfalse
Dtrue\nfalse\ntrue
Attempts:
2 left
💡 Hint
Consider how Optional Equatable compares values and nil.

Practice

(1/5)
1. What does conditional conformance in Swift allow you to do?
easy
A. Make a generic type conform to a protocol only if its generic parameters conform
B. Force all types to conform to a protocol regardless of their generic parameters
C. Automatically generate protocol methods without implementation
D. Conform a type to multiple protocols at once without conditions

Solution

  1. Step 1: Understand generic types and protocols

    Generic types can have parameters that may or may not conform to protocols.
  2. Step 2: Role of conditional conformance

    Conditional conformance allows a generic type to conform to a protocol only if its generic parameters also conform to that protocol.
  3. Final Answer:

    Make a generic type conform to a protocol only if its generic parameters conform -> Option A
  4. Quick Check:

    Conditional conformance = generic type depends on parameter conformance [OK]
Hint: Think: 'Conformance depends on generic parameters' [OK]
Common Mistakes:
  • Assuming all generic types conform unconditionally
  • Confusing conditional conformance with protocol inheritance
  • Believing conditional conformance auto-implements methods
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

  1. Step 1: Recall Swift conditional conformance syntax

    Use where clause after the protocol conformance list to specify conditions.
  2. 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.
  3. Final Answer:

    struct Box<T>: Equatable where T: Equatable {} -> Option A
  4. Quick Check:

    Correct syntax uses 'where' after protocol list [OK]
Hint: Remember: 'where' clause follows protocol conformance [OK]
Common Mistakes:
  • Placing 'where' before protocol conformance
  • Using 'if' instead of 'where'
  • Using '==' instead of ':' in constraints
3. Consider the following Swift code:
struct Wrapper<T> {}
extension Wrapper: Equatable where T: Equatable {
    static func ==(lhs: Wrapper<T>, rhs: Wrapper<T>) -> Bool {
        return true
    }
}

let a = Wrapper<Int>()
let b = Wrapper<Int>()
print(a == b)

What will be the output?
medium
A. false
B. true
C. Compilation error due to missing Equatable conformance
D. Runtime error

Solution

  1. Step 1: Check conditional conformance applicability

    Wrapper conforms to Equatable only if T conforms to Equatable. Int conforms to Equatable, so Wrapper<Int> conforms.
  2. Step 2: Analyze equality operator implementation

    The == operator always returns true regardless of instance state.
  3. Final Answer:

    true -> Option B
  4. Quick Check:

    Conditional conformance applies, operator returns true [OK]
Hint: Check if generic type meets condition, then see operator logic [OK]
Common Mistakes:
  • Assuming default Equatable implementation is used
  • Thinking compilation fails without explicit Equatable conformance
  • Expecting false because instances are different
4. Identify the error in this Swift code snippet:
struct Container<T> {}
extension Container: Hashable where T: Equatable {
    func hash(into hasher: inout Hasher) {
        // implementation
    }
}
medium
A. No error; code is correct
B. Missing 'static' keyword in hash(into:) method
C. Extension syntax is invalid; 'where' clause misplaced
D. Cannot conform to Hashable with only T: Equatable; T must be Hashable

Solution

  1. Step 1: Understand Hashable requirements

    To conform to Hashable, all stored properties must be Hashable. Here, T must conform to Hashable, not just Equatable.
  2. Step 2: Check the constraint in the code

    The code requires T: Equatable, which is insufficient for Hashable conformance.
  3. Final Answer:

    Cannot conform to Hashable with only T: Equatable; T must be Hashable -> Option D
  4. 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

  1. Step 1: Understand multiple constraints in 'where' clause

    Swift allows multiple constraints separated by commas in the where clause.
  2. 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.
  3. Final Answer:

    extension Pair: Codable where A: Codable, B: Codable {} -> Option C
  4. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard