Are Custom Synthesized Conditional Conformances Possible in Swift?

302 Views Asked by At

Is there a way to create a custom Protocol in swift and make the compiler automatically synthesize conformance when all properties conform to the custom protocol by declaring some rules on how to combine the properties?

Right now the standard Codable, Equatable and Hashable Protocols use this behavior, but I am not sure if we are able to declare our own Protocols to behave like this.

Toy Example:

I would like to illustrate with a simple example I am trying to implement. I have created a Protocol called Interpolatable

    protocol Interpolatable {

        func interpolate(to endValue: Self, at ratio: CGFloat) -> Self

    }

What I would like to do is declare a Struct called Keyframe: Interpolatable storing only properties which conforms to the Interpolatable protocol.

    struct Keyframe: Interpolatable {

        let customValue1: CustomValueType1 //conforms to Interpolatable 
        let customValue2: CustomValueType2 //conforms to Interpolatable 

    }

Now I would like to be able to somewhere else declare a Generic way to tell the compiler how to make types like these implement the necessary function to conform to the Interpolatable protocol.

Is this possible? It certainly feels very Schwifty.

0

There are 0 best solutions below