Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 快速泛型复杂继承_Swift_Generics_Inheritance_Compiler Errors - Fatal编程技术网

Swift 快速泛型复杂继承

Swift 快速泛型复杂继承,swift,generics,inheritance,compiler-errors,Swift,Generics,Inheritance,Compiler Errors,以下Swift代码未编译: class Entity { } class EntityConverter<T: Entity> { } class GetEntityServerAction<T: Entity, C: EntityConverter<T>> { } class GetEntityListServerAction<T: Entity, C: EntityConverter<T>>: GetEntityServ

以下Swift代码未编译:

class Entity {

}

class EntityConverter<T: Entity> {

}

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

}

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

}
类实体{
}
类实体转换器{
}
类GetEntityServerAction{
}
类GetEntityListServerAction:GetEntityServerAction{
}
错误如下:

Type 'C' does not inherit from 'EntityConverter<T>'
类型“C”不从“EntityConverter”继承
用于
GetEntityListServerAction
类定义。 由于某些原因,编译器看不到C参数的定义与继承它想要的类型完全相同


对于那些习惯于Java或C中复杂的泛型层次结构的人来说,代码应该看起来相当简单,但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>>()
类实体{}
协议EntityConversionType{
//猜猜你说的转换是指什么?
typealias FromEntity:Entity
}
类EntityConverter:EntityConversionType{
typealias FromEntity=FromType
}
类GetEntityServerAction{}
类GetEntityListServerAction:GetEntityServerAction{}
设x=GetEntityListServerAction()

可能
GetEntityServerAction
也可以仅用协议来表示,您还可以将
Entity
EntityConverter
GetEntityListServerAction
转换为结构。

谢谢!这就解决了问题。尽管从代码的角度来看,我不认为在这种特殊情况下使用协议而不是基于类的方法有任何好处。但也许我还没有意识到关联类型的全部力量:)