0

I am making a request to an API which is returning either an Int or String value for the variable of interest milesDriven. Here is the model which parses the response:

struct RandomTypes: Codable {
    var milesDriven: String?
    var other: String?
    var fromDate: String?
    var toDate: String?
    var type: String?
    var displayType: String?
}

I obviously get an error if milesDriven is an Int; so naturally I tried to use Any? as the response type. However, RandomTypes does not conform to the Codable protocol if I use Any?.

How can I accept either a String or an Int while still conforming to the Codable protocol?

  • https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types – user2864740 Apr 23 '21 at 18:46
  • See e.g. https://stackoverflow.com/questions/65224646/how-is-my-codable-struct-supposed-to-look-like-if-the-json-response-returns-a-di/65224750#65224750 - in your case, you would try decoding `String.self` and `Int.self`. – Gereon Apr 23 '21 at 18:48

0 Answers0