Swift: 关联类型where约束

Swift: associated type with where constraint

我想在协议中有 associatedtype 和一个带有 where 的方法来约束关联类型的类型与协议相同,这可能吗?

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()
}

我得到了:

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

谢谢!

T 已经是类型,您不想在约束中执行 T.TypeT.TransformType: Transformable 也是多余的,所以你可以删除它。

应该是:

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