Are Custom Synthesized Conditional Conformances Possible in Swift?
Asked Answered
F

0

6

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.

Fahlband answered 1/10, 2018 at 9:28 Comment(1)
No, the compiler cannot synthesise protocol conformance for custom protocols. Each protocol for which the compiler can synthesise conformance is treated specially by the compiler, there's no generic method to synthesise conformance for any custom protocol.Yuji

© 2022 - 2024 — McMap. All rights reserved.