Skip to Content
Course content

46: Conditional Conformance

Click on the "Edit" button in the top corner of the screen to edit your slide content.

You’ve likely run into a situation where you're building a generic wrapper—maybe a Result type, a Box, or a network Response—and you suddenly realize you want that wrapper to be Equatable. It seems like a no-brainer. If the thing inside the wrapper can be compared, the wrapper itself should be comparable, right?

But as soon as you try to implement it, you hit a wall. I'll show you what I mean using a typical API response wrapper.

struct APIResponse<T> {
    let payload: T
    let statusCode: Int
}

// This is where we hit the snag
extension APIResponse: Equatable {
    static func == (lhs: APIResponse, rhs: APIResponse) -> Bool {
        return lhs.statusCode == rhs.statusCode && lhs.payload == rhs.payload
    }
}

The wall you'll hit with blanket conformance

If you try to compile the code above, Swift is going to complain loudly. It will tell you that T does not conform to Equatable. The compiler is being pedantic for a good reason: you've told it that APIResponse is Equatable regardless of what T is. If I decide to use APIResponse<SomeNonEquatableClass>, your == implementation is suddenly impossible to execute because the payload can't be compared.

Now, the "naive" way to fix this is to just force T to be Equatable at the struct definition level: struct APIResponse<T: Equatable>. I've seen a lot of developers do this early in their careers. The problem is that you've just nuked the flexibility of your type. Now, you can't even create an APIResponse for a type that isn't equatable, even if you don't actually care about comparing those responses. You're restricting the use of your entire type just to satisfy one protocol.

Letting the compiler decide with conditional conformance

This is where conditional conformance comes in. Instead of forcing the restriction on the type itself, we apply the restriction only to the protocol conformance. We essentially tell Swift: "This type is Equatable, but only in the specific cases where the generic payload is also Equatable."

struct APIResponse<T> {
    let payload: T
    let statusCode: Int
}

// Now we are being precise
extension APIResponse: Equatable where T: Equatable {
    static func == (lhs: APIResponse, rhs: APIResponse) -> Bool {
        return lhs.statusCode == rhs.statusCode && lhs.payload == rhs.payload
    }
}

This is a much more elegant contract. If you have an APIResponse<Int>, you can compare two of them. If you have an APIResponse<UIImage> (which isn't Equatable), the code still compiles and you can still use the struct—you just can't use the == operator on it. It’s the best of both worlds.

The trade-off in API discoverability

There is one thing to keep in mind here: it can occasionally confuse the people using your code. Because the conformance is conditional, a developer might see APIResponse in the documentation and assume it's always Equatable, only to find that their specific instance isn't.

I personally think this is a price worth paying. It's far better to have a flexible type that gains capabilities as its constraints are met than a rigid type that prevents you from using it in common scenarios. You'll see this pattern everywhere in the Swift Standard Library—Array is a prime example. An Array isn't always Equatable; it's only Equatable if the elements it holds are Equatable. Why reinvent the wheel when the language provides this exact mechanism?




📋 Practical Task

Implementing Hashable for a Generic Cache Wrapper

You are building a caching system. You have a generic wrapper called CacheEntry<T> that stores a value and a timestamp of when it was cached. You want to be able to use CacheEntry as a key in a Set or as a key in a Dictionary, which requires the type to conform to Hashable.

Your Task:

  • Create a struct CacheEntry<T> with two properties: value: T and timestamp: Date.
  • Implement Hashable for CacheEntry using conditional conformance, so that it is only Hashable if T is also Hashable.
  • Verify your implementation by creating a Set of CacheEntry<String> (this should work) and attempting to create a Set of CacheEntry<UIView> (this should fail to compile).
Rating
0 0

There are no comments for now.

to be the first to leave a comment.