[英]Swift protocol with associatedtype error
我創建了一個函數類: Bar
, Bar
使用屬於它的委托做特定的事情,這個委托符合協議FooDelegate
,類似的東西:
protocol FooDelegate{
associatedtype Item
func invoke(_ item:Item)
}
class SomeFoo:FooDelegate{
typealias Item = Int
func invoke(_ item: Int) {
//do something...
}
}
class Bar{
//In Bar instance runtime ,it will call delegate to do something...
var delegate:FooDelegate!
}
但在類Bar: var delegate:FooDelegate!
我收到一個錯誤:
協議'FooDelegate'只能用作通用約束,因為它具有Self或相關類型要求
我怎么能解決這個問題?
你有幾個選擇。
首先,您可以使用特定類型的FooDelegate
,例如SomeFoo
:
class Bar {
//In Bar instance runtime ,it will call delegate to do something...
var delegate: SomeFoo!
}
或者您可以使Bar
通用並定義委托所需的Item
類型:
class Bar<F> where F: FooDelegate, F.Item == Int {
//In Bar instance runtime ,it will call delegate to do something...
var delegate: F!
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.