我想在协议(protocol)内声明一个具有关联类型的协议(protocol)。
我知道将其声明为类而不是协议(protocol)可以解决问题。
但我想在协议(protocol)内使用它。
有没有办法使用泛型或类型别名等协议(protocol)来使用协议(protocol)中的关联类型?
protocol A {
associatedtype T
}
protocol B {
var a: A { get } // error. protocol 'A' can only be used as a generic constraint because it has Self or associated type requirements
// But I want set a.T = Int
}
最佳答案
如果您确实要将 A.T
设置为 Int
,您可以在 B: 内的关联类型 where
子句中指定该值
protocol A {
associatedtype T
}
protocol B {
associatedtype U: A where U.T == Int
var a: U { get }
}
或者,您不想将 B
锁定为仅一种特定的 A.T
类型,您可以引入另一种 linkedtype
,它链接回A
:
protocol A {
associatedtype T
}
protocol B {
associatedtype T
associatedtype U: A where U.T == T
var a: U { get }
}
参见Associated Types with a Generic Where Clause Swift 编程语言。
关于swift - 是否可以在协议(protocol)内声明具有关联类型的协议(protocol)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70021694/