2

I have multiple responses which has similar pattern but one key value has always different object in response of json which i want to decode in base model where one key has variety of object type.

Response be like,

{
"status": true,
"message": "Success",
"data":[]
}

Here in data response it has any kind of array of objects or any single object

struct BaseResponseModel: Codable {
    var status: Bool
    var message: String
    var data: DataClass
    
    enum CodingKeys: String, CodingKey {
        case message
        case data
        case status
    }
}

what we can do here to make it single class with data type object pass,

Anyone please..!

1 Answer 1

2

Use Swift generics, and provide the type only at the time of decoding:

struct BaseResponseModel<DataType: Codable>: Codable {
    var status: Bool
    var message: String
    var data: DataType
}

Usage:

let myData = try JSONDecoder().decode(BaseResponseModel<MyStruct>.self, from: data).data // For object
let myData = try JSONDecoder().decode(BaseResponseModel<[MyStruct]>.self, from: data).data // For array

Note: You don't need CodingKeys if the rawValues are the same.

Sign up to request clarification or add additional context in comments.

2 Comments

DataType is not always single object, it may be array of objects, How it work?
Added usage example for object and array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.