Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extend @objc protocol with Hashable in Swift

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?

like image 919
kikettas Avatar asked Oct 16 '22 20:10

kikettas


1 Answers

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.

like image 198
AaoIi Avatar answered Oct 21 '22 02:10

AaoIi