Search code examples
swiftgenericsprotocols

Swift: associated type with where constraint


I want to have associatedtype in protocol and a method with where to constraint the type of associated type to be the same as the protocol, is it possible?

protocol Transformable {
    associatedtype TransformType
    func transform() -> TransformType
}

func repeatTransform<T: Transformable>(_ transformable: T) where T.TransformType: Transformable, T.TransformType == T.Type {
    let t1 = transformable.transform()
    let t2 = t1.transform()
}

I got:

Same-type constraint type 'T.Type' does not conform to required protocol 'Transformable'

Thanks!


Solution

  • T is already the type, you don't want to do T.Type in the constraint. T.TransformType: Transformable is also redundant, so you can remove that.

    It should be:

    func repeatTransform<T: Transformable>(_ transformable: T) where T.TransformType == T