Home > Blockchain >  Make enum with return Class inheriting Codable to parse JSON to your model class
Make enum with return Class inheriting Codable to parse JSON to your model class

Time:04-29

I need to make an enum to return class type to using in another function to parse my JSON to model.

Below follows an example of what I wrote.

enum APIType {
  case status

  var responseType: AnyClass {
    switch self {
    case .status:
      return MyModel.self
    }
  }
}

But, one error occurred which I assume is happening due to Codable inheritance.

Cannot convert return expression of type 'MyClass.Type' to return type 'AnyClass' (aka 'AnyObject.Type')

Has anyone gone through this challenge? How do I resolve this?

CodePudding user response:

The error is actually quite clear, you are trying to return the class type of an object, but the compiler expects a concrete implementation of any class.

Just replace the return value of responseType to be AnyObject.Type

class MyModel {

}
enum APIType {
  case status

    var responseType: AnyObject.Type {
    switch self {
    case .status:
      return MyModel.self
    }
  }
}
print(APIType.status.responseType) // MyModel
  • Related