I have some enum values that I would like to cast to a JSONDecoder Decodable.Protocol type
that can be used in the decode
method.
Each of the Attributes enums Correspond to a Codable
class.
enum Attributes : String {
case Shapes = "GetShapes"
case Color = "GetColors"
case Size = "GetSizes"
}
Instead of having a bunch of switch statements I thought I could dynamically cast the enum to the correct Protocol and save myself a lot of code.
For example
let results = try? JSONDecoder().decode(GetShapes.self, from: jsonData)
Notice that GetShapes.self
, corresponds to an Attributes enum's value.
So I tried using NSProtocolFromString
but that doesn't seem to do the trick.
if let protoRef = NSProtocolFromString(anAttribute.rawValue) {
if let results = try? JSONDecoder().decode(protoRef, from: jsonData) {
//Do something
}
Being able to cast the string to the protocol would save me a lot of work.
Hopefully this clarifies:
Basically, take a string "GetShapes", use some MagicMethod() so it spits out
GetShapes.self
that satisfies the type parameter of the JSONDecoder().decode(type: Decodable.Protocol, from: Data)
Some method like this:
func magicMethod(_ string: String) -> Decodable.Protocol {
}
Is this possible with Swift 4?