簡體   English   中英

如何實現符合相互關聯協議之一的泛型類?

[英]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”; 你想添加它嗎?

我試圖解決它的所有嘗試都沒有成功,他們只是更改了錯誤消息。
有可能嗎? 如何?

以我目前的知識,我認為不可能做你想做的事。 我正在尋找更多信息,我找到了一些關於為什么不需要它的信息。

為什么 Swift 沒有 F-Bounded

支持 F 有界多態性?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM