0

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?

user-44651
  • 3,924
  • 6
  • 41
  • 87
  • You can only decode **types** not single properties or cases. And all `NS...FromString` methods are Objective-C related API which don't work with the native Swift counterparts. – vadian Oct 10 '18 at 17:00
  • What would you recommend in this case? I don't want to have to create a switch statement for every enum. – user-44651 Oct 10 '18 at 17:02
  • I don't know what you are looking for. In case of the enum your dictionary can contain `["foo": "GetShapes"]`, `["foo": "GetColors"]` or `["foo": "GetSizes"]` and if `Attributes` conforms to `Decodable` you can decode `let foo = try container.decode(Attributes.self, forKey: .foo)` – vadian Oct 10 '18 at 17:10
  • @vadian I edited my question, hopefully it will make sense now. – user-44651 Oct 10 '18 at 17:16
  • I'm still confused after your clarification, but I don't think your magic method is the answer. Do you have a class or a struct that is of type `GetShapes`, and you've created an enum with a list of your types? What type do you expect `results` to be after the above code executes? – Jerry Oct 11 '18 at 00:48

0 Answers0