Swift 4 Codable : Common struct for all model












3















Here i am getting API response of all of my api.



{
"success" : true,
"message" : "",
"data" : {
/multipal data parameter/
}
}


And here is my codable model



struct Login: Codable {
let success: Bool
let message: String
let data: Data

struct Data: Codable {

}
}


How can i create common Sturct for success and message parameter.










share|improve this question























  • if success and message come in another dictionary then it can be do

    – Saurabh Jain
    Sep 25 '18 at 13:32






  • 2





    Login is a "common struct for success and message parameter".

    – matt
    Sep 25 '18 at 13:32











  • @matt and what for other parameter, any example would be helpful

    – Bhavesh Dhaduk
    Sep 25 '18 at 13:40
















3















Here i am getting API response of all of my api.



{
"success" : true,
"message" : "",
"data" : {
/multipal data parameter/
}
}


And here is my codable model



struct Login: Codable {
let success: Bool
let message: String
let data: Data

struct Data: Codable {

}
}


How can i create common Sturct for success and message parameter.










share|improve this question























  • if success and message come in another dictionary then it can be do

    – Saurabh Jain
    Sep 25 '18 at 13:32






  • 2





    Login is a "common struct for success and message parameter".

    – matt
    Sep 25 '18 at 13:32











  • @matt and what for other parameter, any example would be helpful

    – Bhavesh Dhaduk
    Sep 25 '18 at 13:40














3












3








3


1






Here i am getting API response of all of my api.



{
"success" : true,
"message" : "",
"data" : {
/multipal data parameter/
}
}


And here is my codable model



struct Login: Codable {
let success: Bool
let message: String
let data: Data

struct Data: Codable {

}
}


How can i create common Sturct for success and message parameter.










share|improve this question














Here i am getting API response of all of my api.



{
"success" : true,
"message" : "",
"data" : {
/multipal data parameter/
}
}


And here is my codable model



struct Login: Codable {
let success: Bool
let message: String
let data: Data

struct Data: Codable {

}
}


How can i create common Sturct for success and message parameter.







ios swift swift4 codable






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Sep 25 '18 at 13:27









Bhavesh DhadukBhavesh Dhaduk

1,2491021




1,2491021













  • if success and message come in another dictionary then it can be do

    – Saurabh Jain
    Sep 25 '18 at 13:32






  • 2





    Login is a "common struct for success and message parameter".

    – matt
    Sep 25 '18 at 13:32











  • @matt and what for other parameter, any example would be helpful

    – Bhavesh Dhaduk
    Sep 25 '18 at 13:40



















  • if success and message come in another dictionary then it can be do

    – Saurabh Jain
    Sep 25 '18 at 13:32






  • 2





    Login is a "common struct for success and message parameter".

    – matt
    Sep 25 '18 at 13:32











  • @matt and what for other parameter, any example would be helpful

    – Bhavesh Dhaduk
    Sep 25 '18 at 13:40

















if success and message come in another dictionary then it can be do

– Saurabh Jain
Sep 25 '18 at 13:32





if success and message come in another dictionary then it can be do

– Saurabh Jain
Sep 25 '18 at 13:32




2




2





Login is a "common struct for success and message parameter".

– matt
Sep 25 '18 at 13:32





Login is a "common struct for success and message parameter".

– matt
Sep 25 '18 at 13:32













@matt and what for other parameter, any example would be helpful

– Bhavesh Dhaduk
Sep 25 '18 at 13:40





@matt and what for other parameter, any example would be helpful

– Bhavesh Dhaduk
Sep 25 '18 at 13:40












2 Answers
2






active

oldest

votes


















3














You can make the root struct representing the network response generic, this will allow you to keep the success and message parts common between all specialised responses.



struct NetworkResponse<ResponseData:Codable>: Codable {
let success: Bool
let message: String
let data: ResponseData
}


You shouldn't create custom types with the same name as built in types, since that will lead to confusion, especially for other people reading your code, so I renamed your custom Data type to ResponseData.



For instance you can create a LoginResponse model and decode it like below. You can do the same for other responses from the same API.



let loginResponse = """
{
"success" : true,
"message" : "",
"data" : {
"username":"test",
"token":"whatever"
}
}
"""

struct LoginResponse: Codable {
let username: String
let token: String
}

do {
print(try JSONDecoder().decode(NetworkResponse<LoginResponse>.self, from: Data(loginResponse.utf8)))
} catch {
print(error)
}





share|improve this answer


























  • Generic would be good but how to decode response with generics with NetworkResponse

    – Bhavesh Dhaduk
    Sep 25 '18 at 13:45











  • @BhaveshDhaduk check my updated answer I've added an example

    – Dávid Pásztor
    Sep 25 '18 at 13:56











  • @AshleyMills ResponseData is a type itself, which conforms to Codable, so in the custom initialiser of NetworkResponse, you can simply decode ResponseData just like you would for a non-generic type conforming to Codable.

    – Dávid Pásztor
    Sep 25 '18 at 15:30



















0














Common structure :



My common struture of model



I have created something like that



struct statusModel<T:Codable>: Codable {

let message : String
let resultData : [T]?
let status : Int

enum CodingKeys: String, CodingKey {
case message = "message"
case resultData = "resultData"
case status = "status"
}
}


Regular model (resultData)



struct modelInitialize : Codable {

let profileimgurl : String?
let projecturl : String?

enum CodingKeys: String, CodingKey {
case profileimgurl = "profileimgurl"
case projecturl = "projecturl"
}
}


You can set like as below



    do {
guard let reponseData = responseData.value else {return} //Your webservice response in Data
guard let finalModel = try?JSONDecoder().decode(statusModel<modelInitialize>.self, from: reponseData) else {return}
}





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f52499383%2fswift-4-codable-common-struct-for-all-model%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    3














    You can make the root struct representing the network response generic, this will allow you to keep the success and message parts common between all specialised responses.



    struct NetworkResponse<ResponseData:Codable>: Codable {
    let success: Bool
    let message: String
    let data: ResponseData
    }


    You shouldn't create custom types with the same name as built in types, since that will lead to confusion, especially for other people reading your code, so I renamed your custom Data type to ResponseData.



    For instance you can create a LoginResponse model and decode it like below. You can do the same for other responses from the same API.



    let loginResponse = """
    {
    "success" : true,
    "message" : "",
    "data" : {
    "username":"test",
    "token":"whatever"
    }
    }
    """

    struct LoginResponse: Codable {
    let username: String
    let token: String
    }

    do {
    print(try JSONDecoder().decode(NetworkResponse<LoginResponse>.self, from: Data(loginResponse.utf8)))
    } catch {
    print(error)
    }





    share|improve this answer


























    • Generic would be good but how to decode response with generics with NetworkResponse

      – Bhavesh Dhaduk
      Sep 25 '18 at 13:45











    • @BhaveshDhaduk check my updated answer I've added an example

      – Dávid Pásztor
      Sep 25 '18 at 13:56











    • @AshleyMills ResponseData is a type itself, which conforms to Codable, so in the custom initialiser of NetworkResponse, you can simply decode ResponseData just like you would for a non-generic type conforming to Codable.

      – Dávid Pásztor
      Sep 25 '18 at 15:30
















    3














    You can make the root struct representing the network response generic, this will allow you to keep the success and message parts common between all specialised responses.



    struct NetworkResponse<ResponseData:Codable>: Codable {
    let success: Bool
    let message: String
    let data: ResponseData
    }


    You shouldn't create custom types with the same name as built in types, since that will lead to confusion, especially for other people reading your code, so I renamed your custom Data type to ResponseData.



    For instance you can create a LoginResponse model and decode it like below. You can do the same for other responses from the same API.



    let loginResponse = """
    {
    "success" : true,
    "message" : "",
    "data" : {
    "username":"test",
    "token":"whatever"
    }
    }
    """

    struct LoginResponse: Codable {
    let username: String
    let token: String
    }

    do {
    print(try JSONDecoder().decode(NetworkResponse<LoginResponse>.self, from: Data(loginResponse.utf8)))
    } catch {
    print(error)
    }





    share|improve this answer


























    • Generic would be good but how to decode response with generics with NetworkResponse

      – Bhavesh Dhaduk
      Sep 25 '18 at 13:45











    • @BhaveshDhaduk check my updated answer I've added an example

      – Dávid Pásztor
      Sep 25 '18 at 13:56











    • @AshleyMills ResponseData is a type itself, which conforms to Codable, so in the custom initialiser of NetworkResponse, you can simply decode ResponseData just like you would for a non-generic type conforming to Codable.

      – Dávid Pásztor
      Sep 25 '18 at 15:30














    3












    3








    3







    You can make the root struct representing the network response generic, this will allow you to keep the success and message parts common between all specialised responses.



    struct NetworkResponse<ResponseData:Codable>: Codable {
    let success: Bool
    let message: String
    let data: ResponseData
    }


    You shouldn't create custom types with the same name as built in types, since that will lead to confusion, especially for other people reading your code, so I renamed your custom Data type to ResponseData.



    For instance you can create a LoginResponse model and decode it like below. You can do the same for other responses from the same API.



    let loginResponse = """
    {
    "success" : true,
    "message" : "",
    "data" : {
    "username":"test",
    "token":"whatever"
    }
    }
    """

    struct LoginResponse: Codable {
    let username: String
    let token: String
    }

    do {
    print(try JSONDecoder().decode(NetworkResponse<LoginResponse>.self, from: Data(loginResponse.utf8)))
    } catch {
    print(error)
    }





    share|improve this answer















    You can make the root struct representing the network response generic, this will allow you to keep the success and message parts common between all specialised responses.



    struct NetworkResponse<ResponseData:Codable>: Codable {
    let success: Bool
    let message: String
    let data: ResponseData
    }


    You shouldn't create custom types with the same name as built in types, since that will lead to confusion, especially for other people reading your code, so I renamed your custom Data type to ResponseData.



    For instance you can create a LoginResponse model and decode it like below. You can do the same for other responses from the same API.



    let loginResponse = """
    {
    "success" : true,
    "message" : "",
    "data" : {
    "username":"test",
    "token":"whatever"
    }
    }
    """

    struct LoginResponse: Codable {
    let username: String
    let token: String
    }

    do {
    print(try JSONDecoder().decode(NetworkResponse<LoginResponse>.self, from: Data(loginResponse.utf8)))
    } catch {
    print(error)
    }






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Sep 25 '18 at 13:55

























    answered Sep 25 '18 at 13:32









    Dávid PásztorDávid Pásztor

    21.7k82749




    21.7k82749













    • Generic would be good but how to decode response with generics with NetworkResponse

      – Bhavesh Dhaduk
      Sep 25 '18 at 13:45











    • @BhaveshDhaduk check my updated answer I've added an example

      – Dávid Pásztor
      Sep 25 '18 at 13:56











    • @AshleyMills ResponseData is a type itself, which conforms to Codable, so in the custom initialiser of NetworkResponse, you can simply decode ResponseData just like you would for a non-generic type conforming to Codable.

      – Dávid Pásztor
      Sep 25 '18 at 15:30



















    • Generic would be good but how to decode response with generics with NetworkResponse

      – Bhavesh Dhaduk
      Sep 25 '18 at 13:45











    • @BhaveshDhaduk check my updated answer I've added an example

      – Dávid Pásztor
      Sep 25 '18 at 13:56











    • @AshleyMills ResponseData is a type itself, which conforms to Codable, so in the custom initialiser of NetworkResponse, you can simply decode ResponseData just like you would for a non-generic type conforming to Codable.

      – Dávid Pásztor
      Sep 25 '18 at 15:30

















    Generic would be good but how to decode response with generics with NetworkResponse

    – Bhavesh Dhaduk
    Sep 25 '18 at 13:45





    Generic would be good but how to decode response with generics with NetworkResponse

    – Bhavesh Dhaduk
    Sep 25 '18 at 13:45













    @BhaveshDhaduk check my updated answer I've added an example

    – Dávid Pásztor
    Sep 25 '18 at 13:56





    @BhaveshDhaduk check my updated answer I've added an example

    – Dávid Pásztor
    Sep 25 '18 at 13:56













    @AshleyMills ResponseData is a type itself, which conforms to Codable, so in the custom initialiser of NetworkResponse, you can simply decode ResponseData just like you would for a non-generic type conforming to Codable.

    – Dávid Pásztor
    Sep 25 '18 at 15:30





    @AshleyMills ResponseData is a type itself, which conforms to Codable, so in the custom initialiser of NetworkResponse, you can simply decode ResponseData just like you would for a non-generic type conforming to Codable.

    – Dávid Pásztor
    Sep 25 '18 at 15:30













    0














    Common structure :



    My common struture of model



    I have created something like that



    struct statusModel<T:Codable>: Codable {

    let message : String
    let resultData : [T]?
    let status : Int

    enum CodingKeys: String, CodingKey {
    case message = "message"
    case resultData = "resultData"
    case status = "status"
    }
    }


    Regular model (resultData)



    struct modelInitialize : Codable {

    let profileimgurl : String?
    let projecturl : String?

    enum CodingKeys: String, CodingKey {
    case profileimgurl = "profileimgurl"
    case projecturl = "projecturl"
    }
    }


    You can set like as below



        do {
    guard let reponseData = responseData.value else {return} //Your webservice response in Data
    guard let finalModel = try?JSONDecoder().decode(statusModel<modelInitialize>.self, from: reponseData) else {return}
    }





    share|improve this answer




























      0














      Common structure :



      My common struture of model



      I have created something like that



      struct statusModel<T:Codable>: Codable {

      let message : String
      let resultData : [T]?
      let status : Int

      enum CodingKeys: String, CodingKey {
      case message = "message"
      case resultData = "resultData"
      case status = "status"
      }
      }


      Regular model (resultData)



      struct modelInitialize : Codable {

      let profileimgurl : String?
      let projecturl : String?

      enum CodingKeys: String, CodingKey {
      case profileimgurl = "profileimgurl"
      case projecturl = "projecturl"
      }
      }


      You can set like as below



          do {
      guard let reponseData = responseData.value else {return} //Your webservice response in Data
      guard let finalModel = try?JSONDecoder().decode(statusModel<modelInitialize>.self, from: reponseData) else {return}
      }





      share|improve this answer


























        0












        0








        0







        Common structure :



        My common struture of model



        I have created something like that



        struct statusModel<T:Codable>: Codable {

        let message : String
        let resultData : [T]?
        let status : Int

        enum CodingKeys: String, CodingKey {
        case message = "message"
        case resultData = "resultData"
        case status = "status"
        }
        }


        Regular model (resultData)



        struct modelInitialize : Codable {

        let profileimgurl : String?
        let projecturl : String?

        enum CodingKeys: String, CodingKey {
        case profileimgurl = "profileimgurl"
        case projecturl = "projecturl"
        }
        }


        You can set like as below



            do {
        guard let reponseData = responseData.value else {return} //Your webservice response in Data
        guard let finalModel = try?JSONDecoder().decode(statusModel<modelInitialize>.self, from: reponseData) else {return}
        }





        share|improve this answer













        Common structure :



        My common struture of model



        I have created something like that



        struct statusModel<T:Codable>: Codable {

        let message : String
        let resultData : [T]?
        let status : Int

        enum CodingKeys: String, CodingKey {
        case message = "message"
        case resultData = "resultData"
        case status = "status"
        }
        }


        Regular model (resultData)



        struct modelInitialize : Codable {

        let profileimgurl : String?
        let projecturl : String?

        enum CodingKeys: String, CodingKey {
        case profileimgurl = "profileimgurl"
        case projecturl = "projecturl"
        }
        }


        You can set like as below



            do {
        guard let reponseData = responseData.value else {return} //Your webservice response in Data
        guard let finalModel = try?JSONDecoder().decode(statusModel<modelInitialize>.self, from: reponseData) else {return}
        }






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Dec 31 '18 at 11:04









        kalpeshkalpesh

        7521822




        7521822






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f52499383%2fswift-4-codable-common-struct-for-all-model%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Monofisismo

            Angular Downloading a file using contenturl with Basic Authentication

            Olmecas