How can I group TableView items from a struct in swift?

Viewed 37

In my case I have struct with data and I would like use value _host to titleForHeaderInSection in tableview and group by _host data

  var polozkyuctu = [polozky]()
    
    struct polozky: Codable {
        let _id: Int
        let _recept: String
        let _host: String
        }
Data in polozkyuctu:
[Cheers.Ucet.polozky(_id: 453741,  _recept: "BECHEROVKA 1L", _host: "0"), 
Cheers.Ucet.polozky(_id: 453718,  _recept: "PALAČINKY DEZERT", _host: "10“), 
Cheers.Ucet.polozky(_id: 453719,  _recept: "TLAČENKA SVĚTLÁ S CIBULÍ", _host: "10“),
Cheers.Ucet.polozky(_id: 453720,  _recept: "PAŠTIKA JÁTROVÁ",  _host: "0"), 
Cheers.Ucet.polozky(_id: 453737,  _recept: "ABSINTH ŽUFÁNEK 0,5L", _host: "2")]

extension Ucet: UITableViewDataSource {
      
        func numberOfSections(in tableView: UITableView) -> Int {
         
            let hh = Dictionary(grouping: polozkyuctu, by: { (element: polozky) in
                return element._host })
            
            print ("hostcount: \(hh.count)")
            // hostcount: 3
            return hh.count
        }
        
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return ???
             }
        
        func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
            return „Title \(???)“
           }
            
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            
           let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
          ???

        return cell
            
        }
    

How to fit the "section" correctly so that the result looks in datatable like this?

Title 0
BECHEROVKA 1L
PAŠTIKA JÁTROVÁ

Title 2
ABSINTH ŽUFÁNEK 0,5L

Title 10
PALAČINKY DEZERT
TLAČENKA SVĚTLÁ S CIBULÍ

1 Answers

Unless you have a huge data set, you should transform your array so that you can easily read out the desired values:

struct Polozky: Codable {
        let _id: Int
        let _recept: String
        let _host: String
        }
let data = [Polozky(_id: 453741,  _recept: "BECHEROVKA 1L", _host: "0"),
            Polozky(_id: 453718,  _recept: "PALAČINKY DEZERT", _host: "10"),
            Polozky(_id: 453719,  _recept: "TLAČENKA SVĚTLÁ S CIBULÍ", _host: "10"),
            Polozky(_id: 453720,  _recept: "PAŠTIKA JÁTROVÁ",  _host: "0"),
            Polozky(_id: 453737,  _recept: "ABSINTH ŽUFÁNEK 0,5L", _host: "2")]


// transform your data 
let grouped = Dictionary(grouping: data, by: { $0._host })
let sorted = grouped.sorted { $0.key.localizedStandardCompare($1.key) == .orderedAscending }
// now easily get you datasource values like so
let someSection = 1
let sectionTitle = sorted[someSection].key             // "2"
let sectionRowCount = sorted[someSection].value.count  // 1

Related