我想在協議內宣告一個帶有關聯型別的協議。
我知道將它宣告為一個類而不是一個協議可以解決這個問題。
但我想在協議中使用它。
有沒有辦法使用泛型或型別別名之類的東西在協議中使用具有關聯型別的協議?
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
}
uj5u.com熱心網友回復:
如果您真的想設定A.T為Int,您可以where在 B中的關聯型別子句中指定:
protocol A {
associatedtype T
}
protocol B {
associatedtype U: A where U.T == Int
var a: U { get }
}
或者,您不想B只鎖定一種特定A.T型別,您可以引入另一種 associatedtype,它鏈接回A:
protocol A {
associatedtype T
}
protocol B {
associatedtype T
associatedtype U: A where U.T == T
var a: U { get }
}
見與通用Where子句相關型別的雨燕編程語言。
uj5u.com熱心網友回復:
protocol A {
associatedtype T
var a: T { get }
}
protocol B {
associatedtype U where U: A
var b: U { get }
}
但請記住,由于這兩種相關型別,您將不得不對此進行大量推理。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/360589.html
標籤:迅速
