Compiler failure when using conditional conformance and generic type

See code below. Example 3 doesn't compile. Does anyone know if it's an expected behavior or a limitation of the compiler? I ask because I think it's a valid use case.

@propertyWrapper
struct DummyWrapper<T>: Equatable where T: Equatable {
    var wrappedValue: T

    init(wrappedValue: T) {
        self.wrappedValue = wrappedValue
    }
}

// example 1
struct Test1 {
    @DummyWrapper var x: Int
}

// example 2
struct Test2: Equatable {
    @DummyWrapper var x: Int
}

// example 3: this doesn't compile
// error: Generic struct 'DummyWrapper' requires that 'T' conform to 'Equatable'
struct Test3<T> {
    @DummyWrapper var x: T
}

// example 4: this works
struct Test4<T: Equatable> {
    @DummyWrapper var x: T
}

It's expected behavior. The reason is that your DummyWrapper definition does not declare a conditional conformance.

You wrote this:

@propertyWrapper
struct DummyWrapper<T>: Equatable where T: Equatable { … }

Which is equivalent to this:

@propertyWrapper
struct DummyWrapper<T: Equatable>: Equatable { … }

That is, DummyWrapper unconditionally conforms to Equatable and T must always be Equatable.

A conditional conformance must be declared in an extension, like this:

@propertyWrapper
struct DummyWrapper<T> { … }

extension DummyWrapper: Equatable where T: Equatable {}

With this, example 3 compiles.

1 Like

Thanks! I didn't realize it at all.

Just a note to myself. The generic type in example 3 is just a red herring. And example 1 just happens to work, because Int conforms to Equatable.

1 Like