gpt4 book ai didi

Swift 泛型复杂的继承

转载 作者:可可西里 更新时间:2023-11-01 02:23:20 26 4
gpt4 key购买 nike

以下 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 编译器确实不喜欢某些东西。

最佳答案

您可能会发现使用协议(protocol)和关联类型是更像 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 也可以仅由一个协议(protocol)表示,并且您可以转换 EntityEntityConverterGetEntityListServerAction 到结构,也。

关于Swift 泛型复杂的继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29437919/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com