I’m creating a register view on my app, and I’m trying to decode a json but the key has a different type depending of the response.
If the register success:
{
"data": true,
"success": true
}
if the register fails with many reasons:
{
"data": ["email is not valid", "password must have more than 4 digits"],
"success": false
}
if the register fails with only one reason:
{
"data": "email is not valid",
"success": false
}
How to build a struct in Swift to handle this situations ?
struct Response: Codable {
var data: // what type to use: String? [String]? Bool?
var success: Bool
}
I asked the backend dev but for the moment, there’s no changes on the backside, so I have to do with it …
2
Answers
You can introduce an enumeration with all possible options and provide your custom implementation of init(from decoder: Decoder)
Alternatively you can just have separate properties in your struct and set them accordingly. Enum just looks more Swifty.
In case you can ignore Bool as Joakim suggested, then you can simply have that (no need for enum):
I would define an enum for this result. E.g.,
And I would then have a custom decoder for this:
Note, you mentioned this as being for this particular endpoint, that returned
Bool
upon success. But if they’ve done this for the registration endpoint, I bet they’ve done this for other endpoints, too. So, the above is generic, which in this case, you would use like:But it could easily be used with other
Success
payload types.Note, in this case, you probably don’t care about the
success
payload (i.e., if the registration was successful, then both thesuccess
anddata
keys are likelytrue
; if it wasn’t successful, then thedata
will contain the error messages), but that is a conversation between you and your backend engineers. But you probably want the “let me extract the payload” pattern for those other endpoints where this inconsistent error message pattern is employed.For more information about this custom decoding pattern, see Encoding and Decoding Custom Types.