【问题标题】:Swift generics complex inheritanceSwift 泛型复杂继承
【发布时间】:2015-04-03 18:43:28
【问题描述】:

以下 Swift 代码无法编译:

class Entity {

}

class EntityConverter<T: Entity> {

}

class GetEntityServerAction<T: Entity, C: EntityConverter<T>> {

}

class GetEntityListServerAction<T: Entity, C: EntityConverter<T>>: GetEntityServerAction<T, C> {

}

出现错误:

Type 'C' does not inherit from 'EntityConverter<T>'

对于GetEntityListServerAction 类定义。 由于某些原因,编译器看不到 C 参数的定义就像继承它想要的完全相同的类型。

对于那些习惯于在 Java 或 C# 中使用复杂的泛型层次结构但 Swift 编译器确实不喜欢的人来说,代码应该看起来相当简单。

【问题讨论】:

    标签: swift generics inheritance compiler-errors


    【解决方案1】:

    您可能会发现使用协议和关联类型是更类似于 Swift 的处理方式:

    class Entity { }
    
    protocol EntityConversionType {
        // guessing when you say conversion, you mean from something?
        typealias FromEntity: Entity
    }
    
    class EntityConverter<FromType: Entity>: EntityConversionType {
        typealias FromEntity = FromType
    }
    
    class GetEntityServerAction<T: Entity, C: EntityConversionType where C.FromEntity == T> {  }
    
    class GetEntityListServerAction<T: Entity, C: EntityConversionType where C.FromEntity == T>: GetEntityServerAction<T, C> { }
    
    let x = GetEntityListServerAction<Entity, EntityConverter<Entity>>()
    

    可能GetEntityServerAction 也可以仅由协议表示,您也可以将EntityEntityConverterGetEntityListServerAction 转换为结构。

    【讨论】:

    • 谢谢!这解决了这个问题。即使从代码的角度来看,对于这种特殊情况,我没有看到使用协议而不是基于类的方法的任何优势。但也许我还没有意识到关联类型的全部力量:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多