我有这样的代码:
protocol CoreTypes {
associatedtype TypeA
// ...more types and various operations between them
}
protocol Context<Types> {
associatedtype Types: CoreTypes
var valueA: Types.TypeA { get }
func setValueA(_ b: Types.TypeA)
}
class Operation<Types: CoreTypes> {
var context: any Context<Types>
init(context: some Context<Types>) {
self.context = context
}
func perform() {
context.setValueA(context.valueA)
}
}
但是,
context.setValueA(context.valueA)
无法编译。错误是:
无法将类型“Any”的值转换为预期参数类型“Types.TypeA”
这就像 Swift 不明白这两个定义使用相同的类型:
var valueA: Types.TypeA { get }
func setValueA(_ b: Types.TypeA)
我知道我可以通过定义
Context<TypeA>
来解决这个特定问题,但我需要间接使用它,即来自 Types.TypeA
。有办法让这个工作吗?
如果我将
Context
转换为类,它也可以正常工作,即:
class Context<Types: CoreTypes> {
var valueA: Types.TypeA { preconditionFailure() }
func setValueA(_ b: Types.TypeA) { preconditionFailure() }
}
这样我就可以从
any
中删除 var context: Context<Types>
,但是使用这些“假抽象类”会使编译时间安全性降低......
那么有没有更好的方法来使用另一种类型的关联类型?