Search code examples
arraysswiftuitableviewdictionarycustom-cell

Is it possible to use a specific keys in a dictionary for a non static tableView with a custom tableViewCell


I have an instance of a class, which i want to use like a dictionary as datasource for a tableView. here is the instance AlimentTest:

class AlimentModificationData {
    
    static var AlimentTest : AlimentObject = AlimentObject(nomAliment: "Amandes", poids: 100, calories: 108, proteines: 21, lipides: 53, glucides: 8, aRetinol: 8, aBetacarotene: 1, vitamineC: 0.8, vitamineB1: 0.18, calcium: 248, omega3: 0.06, comments: "fffffff sdsddsdsd", premierBooleen: false, optimize: false)
    
    static var listNutriments : [String] = ["aRetinol", "aBetacarotene", "vitamineC", "vitamineB1", "calcium", "omega3"]
}

I want to use this instance "AlimentTest" for a tableView, with a customcell with an identifier. But i want to use only the keys which are specified in the static array named listNutriments.

At the end, i want my tableView to display something like this for dequeureusableCell:

aRetinol 8
aBetacarotene 1
vitamineC 0.8
vitamineB1 0.18
calcium 248
omega3 0.06

How can i do that?


Solution

  • create AlimentTest method, that generates the dictionary and then use listNutriments to filter it e.g.

    extension AlimentObject {
        func asDict [String : Any] {
            var dict: [String : Any] = [:]
            dict["nomAliment"] = nomAliment
            dict["poids"] = poids
            dict["calories"] = calories
            dict["proteines"] = proteines
            dict["lipides"] = lipides
    
            ...here fill more info to dict
    
            return dict
        }
    }
    

    Then use it to generate list based on your filter name:

    let filtered =  alimentObject.asDict.filter({ listNutriments.contains($0.key)})
    

    or if you want to make it without manually creating asDict method, use this (based on How to list all Variables of a class in swift):

    extension AlimentObject {
        func listPropertiesWithValues(reflect: Mirror? = nil) -> [String : Any] {
            var dict = [String : Any]()
            let mirror = reflect ?? Mirror(reflecting: self)
            if mirror.superclassMirror != nil {
                self.listPropertiesWithValues(reflect: mirror.superclassMirror)
            }
    
            for (index, attr) in mirror.children.enumerated() {
                if let property_name = attr.label {
                    dict[property_name] = attr.value
                }
            }
        }
    }
    

    and then you would use:

    let filtered =  alimentObject.listPropertiesWithValues().filter({ listNutriments.contains($0.key)})