2

Having a Set of a specific interface in java is very useful:

HashSet<MyInterface> mySet;

Is it possible to do something similar in Swift?

I tried unsuccessfully the following:

public protocol DialogDelegate : class, Hashable
{
    func myFunction()
}

public final class DialogManager: NSObject
{
    private var _dialogDelegates: Set<DialogDelegate>

    private override init()
    {
        _dialogDelegates = Set<DialogDelegate>()
        super.init();
    }
}

I get the compiler error:

Protocol 'DialogDelegate' can only be used as a generic constraint because it has Self or associated type requirements

Unheilig
  • 16,196
  • 193
  • 68
  • 98
codifilo
  • 50
  • 1
  • 5

1 Answers1

0

The problem you're having is explained in: What does "Protocol ... can only be used as a generic constraint because it has Self or associated type requirements" mean?

To solve this you could use DialogDelegate as a generic type constraint:

public final class DialogManager<T: DialogDelegate>: NSObject {
    private var _dialogDelegates: Set<T>

    private override init()
    {
        _dialogDelegates = Set<T>()
        super.init();
    }
}

Bear in mind, this won't allow you allowed to mix the types of objects stored in _dialogDelegates; that may or may not be a problem for you.

Community
  • 1
  • 1
ABakerSmith
  • 22,759
  • 9
  • 68
  • 78
  • 3
    It's so silly that such simple task as creating set of protocols (commonly used when implementing the observer pattern) is impossible. You can't just inherit your protocol from `Hashable`. This solution (as well as all other possible ones) is clumsy and hacky. – kelin May 20 '17 at 19:49
  • I can say I share your anger @kelin. – Gian Franco Zabarino Apr 12 '19 at 19:15