![](/img/trans.png)
[英]How can I set the delegate for a protocol from the child of the destination VC?
[英]How can I create a Set of delegate protocol items in Swift?
假設我有五個都符合特定協議的UIView
對象。 我有一個對象,該對象應維護這些對象的列表,並在必要時向它們發送所有消息。
protocol MyProtocol: AnyObject {
func doSomething()
}
問題是,當我將這些UIView
添加到Set變量時,編譯器會產生錯誤,因為MyProtocol
不符合Hashable
。 我能理解其原因,有人能想到克服此問題的好方法嗎? 同時,我考慮改用NSHashTable,但您卻失去了Sets的出色枚舉功能。
更新答案以發布一些示例代碼(仍然無法正常工作)
protocol MyProtocol: class, AnyObject {
func doSomething()
}
class MyClass {
var observers: Set<MyProtocol> = Set<MyProtocol>()
}
當您為類定義協議時,因此您需要在繼承任何其他協議之前編寫“ class”關鍵字:
protocol MyProtocol: AnyObject, Hashable{
func doSomething()
}
class MyClass<T: MyProtocol> {
var observers: Set<T> = Set<T>()
}
將您的協議更改為此,它將正常工作。 您可以參考Apple文檔以獲取更多詳細信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.