![](/img/trans.png)
[英]How can I implement a generic class that conforms to a protocol with associated type?
[英]How to implement a generic class that conforms one of the mutually associated protocols?
我有兩個協議。 它們中的每個 ( x ) 都包含associatedtype
,當此協議 ( y ) 的associatedtype
等於Self
(of x ) 時,需要確認另一個協議 ( y )。
protocol B {
associatedtype AA: A
where AA.BB == Self
}
protocol A {
associatedtype BB: B
where BB.AA == Self
}
按如下方式實現這些協議是沒有問題的:
class AAA: A {
typealias BB = BBB
}
class BBB: B {
typealias AA = AAA
}
但我不能將其中之一實現為通用的。
class AAA<BBBB: B>: A {
typealias BB = BBBB
}
class BBB: B {
typealias AA = AAA<BBB>
}
結果,我有一個錯誤:
'A' 要求類型 'AAA' 和 'BBBB.AA' 是等價的
並注意:
要求指定為 'Self' == 'Self.BB.AA' [與 Self = AAA]
聽起來可以理解。 我將約束添加到我的泛型類中。
class AAA<BBBB: B>: A where BBBB.AA == AAA {
typealias BB = BBBB
}
結果
錯誤:類型“AAA”不符合協議“A”
注意:協議需要嵌套類型“BB”; 你想添加它嗎?錯誤:類型“BBB”不符合協議“B”
注意:協議需要嵌套類型“AA”; 你想添加它嗎?
我試圖解決它的所有嘗試都沒有成功,他們只是更改了錯誤消息。
有可能嗎? 如何?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.