[英]How can I create a Set of delegate protocol items in Swift?
Let's assume I have five UIView
objects which all conform to a particular protocol. 假设我有五个都符合特定协议的
UIView
对象。 I have an object which should maintain a list of these objects, and message them all when necessary. 我有一个对象,该对象应维护这些对象的列表,并在必要时向它们发送所有消息。
protocol MyProtocol: AnyObject {
func doSomething()
}
The problem is, when I go to add these UIView
s to a Set variable, the compiler produces an error because MyProtocol
does not conform to Hashable
. 问题是,当我将这些
UIView
添加到Set变量时,编译器会产生错误,因为MyProtocol
不符合Hashable
。 I can understand the reasoning for this, can anyone think of good ways to overcome this? 我能理解其原因,有人能想到克服此问题的好方法吗? In the meantime I considered using NSHashTable instead, but you lose the nice enumeration features of Sets.
同时,我考虑改用NSHashTable,但您却失去了Sets的出色枚举功能。
Updating answer to post some sample code (this is still not working) 更新答案以发布一些示例代码(仍然无法正常工作)
protocol MyProtocol: class, AnyObject {
func doSomething()
}
class MyClass {
var observers: Set<MyProtocol> = Set<MyProtocol>()
}
As you are defining protocol for class so you need to write 'class' keyword before inheriting any other protocol: 当您为类定义协议时,因此您需要在继承任何其他协议之前编写“ class”关键字:
protocol MyProtocol: AnyObject, Hashable{
func doSomething()
}
class MyClass<T: MyProtocol> {
var observers: Set<T> = Set<T>()
}
Change your protocol to this and it will work fine. 将您的协议更改为此,它将正常工作。 You can refer Apple Documentation for further details.
您可以参考Apple文档以获取更多详细信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.