I'm trying to achieve something similar to--but not quite the same as--the Codable/CodableKeys protocols that Swift4 uses.
Given the following code:
protocol Handler{}
protocol HandlerValues{}
class SomeClass : Handler{
enum MyEnum : String, HandlerValues{
case first
case second
}
}
class SomeOtherClass : Handler{
enum MyEnum : String, HandlerValues{
case third
case fourth
case fifth
}
}
The following statements are guaranteed to be true:
A class that implements
Handler
, must specify an enum that implementsHandlerValues
, or an error will be thrown.That enum's name will always be
MyEnum
(in this example)Any enum that implements
HandlerValues
will always be defined within aHandler
class. (similar toCodableKeys
being defined within aCodable
. Technically this can't be enforced, but if it's defined anywhere else, it's simply ignored.)
What I'm trying to do is one of two things:
- Inside a function that takes a
HandlerValue
as an argument, infer it's containing class, or... - Inside a function that takes a
Handler
as an argument, to be able to enumerate itsHandlerValues
(like how implementations that take aCodable
know how to iterate over itsCodableKeys
enum.)
For the first, my thought is to use String(reflecting:)
, split on '.', lop off the last component, reassemble/join to a string, then get the type based on it. It's three-lefts-to-go-right, but it would get me there.
In the second case, I'm trying to define Handler
in such a way to guarantee it will have a HandlerValues
enum that can be enumerated (again, like Codable
knows it will have a CodableKeys
enum. I just don't know how Codable
defines that.)
I tried this, but of course this doesn't work...
protocol HandlerValues{}
protocol Handler{
enum MyEnum : HandlerValues
}
Update
This seems to be getting me closer...
protocol HandlerValues : RawRepresentable{}
protocol Handler{
associatedtype MyEnum : HandlerValues
}
...but I still don't know how to achieve #2 above (i.e. given a Handler
instance, how can you enumerate the values of its MyEnum
or how do you even guarantee MyEnum
is an enum in the first place?)
So how can that information be obtained?