5
votes

I have an @objc protocol with this implementation:

@objc public protocol Document: class {
   var data: Data? { get }
   var image: UIImage? { get }

   func generatePreview()
} 

And I'm trying to use it in a [Document: Int] dictionary, but naturally I get this error:

Type 'Document' does not conform to protocol 'Hashable'

The problem is that I don't know how to make it conform Hashable, since it is an @objc protocol and Hashable is only available in Swift. If I try to make it conform Hashable, I get this error:

@objc protocol 'Document' cannot refine non-@objc protocol 'Hashable'

This protocol is used as a property in an @objc method, which I want to keep as an '@objc' method since it is part of a @objc delegate protocol.

This protocol looks like this:

@objc public protocol MyClassDelegate: class {

    @objc func methodOne(parameter: [Document: Int])

}

Any idea?

1
What's the purpose of declaring the protocol as @objc?Ahmad F
As I answered to @aaoli, it is used as a parameter in an @objc methodkikettas
Well, ObjC doesn't really care about dictionary key types, so for @objc methods you may just use NSDictionary.user28434'mstep
I know that I can use NSDictionary, but I'm asking this because I want to find a solution which allows me to use type safe dictionaries.kikettas
See stackoverflow.com/questions/49479839/… for another version of this problem. The short answer is: don't use protocols as keys in dictionaries. It never goes well and all the workarounds are a pain. The issue isn't @objc; it's protocols and Hashable.Rob Napier

1 Answers

3
votes

You can use [AnyHashable: Int] which is a type-erased hashable value.

I assume you have the protocol called Document:

@objc public protocol Document: class {
    var data: Data? { get }
    var image: UIImage? { get }

    func generatePreview()
}

And your protocol methodOne will be accepting [AnyHashable: Int]:

@objc public protocol MyClassDelegate: class {

     @objc func methodOne(parameter: [AnyHashable: Int])

}

Its kinda complicated question, after some research i agree with @Rob Napier

don't use protocols as keys in dictionaries. It never goes well and all the workarounds are a pain.

I might not answered perfectly but hopefully that should make the errors goes away.