I feel like the Swift compiler is giving me mixed messages.
I don't understand what the issue is.
This is what I have, and I want those enum to be keys to a dictionary:
protocol ArbitraryKey : CaseIterable, Hashable {}
enum HearNoEvil : ArbitraryKey { case a, b, c }
enum SeeNoEvil : ArbitraryKey { case d, e, f }
enum SpeakNoEvil : ArbitraryKey { case g, h, i }
This is what I want to avoid:
var dictionary : [ AnyHashable : String ] = [:]
This is what I want to do:
var dictionary : [ any ArbitraryKey : String ] = [:]
The protocol ArbitraryKey will eventually have methods I want to be able to invoke on the enums values.
However, the iOS 16.4 / Swift 5.7+ compiler objects to everything I've tried:
If I do this:
protocol ArbitraryKey : CaseIterable, Hashable {}
var dictonary : [ArbitraryKey : String] = [:]
Type 'any ArbitraryKey' cannot conform to 'Hashable'
Use of protocol 'ArbitraryKey' as a type must be written 'any ArbitraryKey'
Replace 'ArbitraryKey' with 'any ArbitraryKey'
So I "fix" it:
protocol ArbitraryKey : CaseIterable, Hashable {}
var dictonary : [any ArbitraryKey : String] = [:] // <-- added 'any'
Type 'any ArbitraryKey' cannot conform to 'Hashable'
So I "fix" that:
protocol ArbitraryKey : CaseIterable {} // <-- removed Hashable
var dictonary : [any ArbitraryKey : String] = [:]
Type 'any ArbitraryKey' does not conform to protocol 'Hashable'
In conclusion:
At this point the chump is stumped.
Can someone explain what is going on?
Any thoughts on a different approach that's clean and straightforward?
If the goal is to make a dictionary where the keys are restricted to the types (enums in your example) which conform to a specific protocol, I can think of creating a specific dict for the protocol.
Here's How to Use:
This also works for types other than enum e.g. struct, but there is a caveat:
If AnyHashable(obj1) and AnyHashable(obj2) are the same, it leads to the same key which may be not what you want. For that case, you can implement a hashing method other than just using AnyHashable.