I need to convert my model to fit data in tableview cell finding better approach

My Model

class MyResponseModel {
    var question: String = ""
    var id: String = ""
    var answer: String = ""
    //Other variables also but not required to display
     init(fromDictionary dictionary: [String:Any]) {
        self.question = (dictionary["question"] as? String) ?? ""
        self.id = (dictionary["id"] as? String) ?? ""
        self.answer = (dictionary["answer"] as? String) ?? ""
    //MARK: Converting model to cell data
    func toModel() -> MyTblCellDetail {
        return MyTblCellDetail(title:self.question,detail:self.answer)
//MARK: Initialize cell data with custom model
struct MyTblCellDetail {
    var title: String = ""
    var detail: String = ""
    var isSelected:Bool = false

    init(title:String,detail:String) {
        self.title = title
        self.detail = detail
    init(data:MyResponseModel) {
        self.title = data.question
        self.detail = data.answer

Note: I am reusing same cell to display most of the data so i will use the same method to converting all class model to MyTblCellDetail struct

So my question is which is better way to do the same or any other approach i can use for the same. Thank you!

  • \$\begingroup\$ I would consider replacing MyTblCellDetail entirely with a protocol. MyResponseModel then conforms to that protocol by providing computed properties called table, detail and isSelected. \$\endgroup\$ – Alexander Oct 9 '20 at 20:45
  • \$\begingroup\$ myResponsemodel is just for demo there are too many responses can you explain more \$\endgroup\$ – Jaydeep Vyas Oct 10 '20 at 11:45
  • \$\begingroup\$ Make a protocol, and make all of your models conform to it. docs.swift.org/swift-book/LanguageGuide/Protocols.html \$\endgroup\$ – Alexander Oct 10 '20 at 13:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.