简体   繁体   English

如何在Swift中创建一组委托协议项?

[英]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.

相关问题 如何从目标 VC 的子级为协议设置委托? - How can I set the delegate for a protocol from the child of the destination VC? 如何以编程方式创建与协议和代理一起使用的segue(swift 3 xcode) - how to programmatically create segue for use with Protocol & Delegate (swift 3 xcode) Swift如何从根VC到嵌入式VC创建协议委托 - Swift how to create a protocol delegate from root VC to embedded VC 如何快速在委托sizeForItemAtIndexPath中创建collectionview单元格的对象 - how can i create object of collectionview Cell in delegate sizeForItemAtIndexPath in swift Swift-委托-如何将协议链接到已实现的委托方法? - Swift - Delegates - How do I link the protocol to the implemented delegate methods? Xamarin Monotouch UISplitViewController:如何设置或创建UISplitViewController的委托? - Xamarin Monotouch UISplitViewController: How can I set or create the delegate for UISplitViewController? 如何在Swift中设置委托 - How to set a delegate in Swift 我如何在目标c中使用segue制定委托协议 - how i can make delegate protocol using segue in objective c 无法使用委托协议在标签中设置值 - Can not set the value in the label using delegate protocol 如何遵循Swift中的Strideable协议? - How can I conform to the Strideable protocol in Swift?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM