如何使用泛型中的 AssociatedType 作为类型?

问题描述 投票:0回答:1

我有这样的代码:

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>
,但是使用这些“假抽象类”会使编译时间安全性降低......

那么有没有更好的方法来使用另一种类型的关联类型?

swift generics associated-types generic-associated-types
1个回答
0
投票

您可以编写通用辅助函数来打开存在类型(SE-0352):

func perform() {
    func helper<T: Context<Types>>(_ x: T) {
        x.setValueA(x.valueA)
    }
    helper(context)
}

也就是说,根据我对 SE-0353 的理解,

context.setValueA(context.valueA)
也应该是可能的,因为
Context
的关联类型被限制为具体类型。

© www.soinside.com 2019 - 2024. All rights reserved.