在TableView中填充数组字典的高效清洁方法 [英] Efficient and Clean way of populating array dictionary in tableview

查看:68
本文介绍了在TableView中填充数组字典的高效清洁方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以告诉用字典数组填充tableView的干净有效的方法吗?我有模型Sale,其中包含saleAmount,soldBy,部门,saleDate.每个部门可能包含许多销售数据,并希望按每个部门来划分销售数据.此外,在tableView标头中,我想显示部门名称以及特定部门的总销售额

Can somebody tell the clean and Efficient way of populating tableView with the array of dictionaries? I have model Sale which contains saleAmount, soldBy, division, saleDate. Each division may contain many Sale data and want to segregate the Sale data by each division. Additionally, in the tableView header, I want to display the division name along with the total sales by a particular division

class Sale  {

    var saleAmount : Double = 0.00 
    var soldBy : String = ""
    var division : String = ""
    var saleDate : Date?
}

我收到数据并存储在

var sales : [Sale] = [Sale]()

然后我将数据处理成每个部门"的字典

and then I process the data into a dictionary for each 'division'

var salesDict : [String : Sale] = [String : Sale] ()
func createIndex<Key, Element>(elms:[Element], extractKey:(Element) -> Key) -> [Key:Element] where Key : Hashable {
        return elms.reduce([Key:Element]()) { (dict, elm) -> [Key:Element] in
            var dict = dict
            dict[extractKey(elm)] = elm
            return dict
        }
    }

salesDict = createIndex(elms: sales, extractKey: {$0.division})
salesSection = salesDict.compactMap(){$0.key} // To store keys

print(saleDict) // ["division1": Clientname.Sale, "division2": Clientname.Sale, "division3": Clientname.Sale, "division4": Clientname.Sale]

并填充tableView

and populating the tableView

func numberOfSections(in tableView: UITableView) -> Int {

       return salesSection.count
    }

数据没有正确填充

Data is not populating correctly

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 

        return [salesDict[salesSection[section]]?.soldBy].count

    }



    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

            let saleItem = salesDict[salesSection[indexPath.section]]
            let cell = tableView.dequeueReusableCell(withIdentifier: "FoldingCell", for: indexPath) as! SaleHistoryTableViewCell

cell.saleAmountLabel.text = ("\(String(describing: saleItem?.saleAmount))")
    }

 func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

        return salesSection[section]
    }

推荐答案

尝试这个游乐场:

import UIKit
import PlaygroundSupport

class Sale {
    var saleAmount : Double = 0.00
    var soldBy : String = ""
    var division : String = ""
    var saleDate : Date?

    init(saleAmount : Double = 0.0, soldBy : String = "" , division : String = "", saleDate : Date? = nil) {
        self.saleAmount = saleAmount
        self.soldBy = soldBy
        self.division = division
        self.saleDate = saleDate
    }
}

class VC: UITableViewController {

    var salesGroupedByDivision: [String: [Sale]]!

    init() {
        super.init(style: .grouped)
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
        let sales = [
            Sale(saleAmount: 1.0, division: "1"),
            Sale(saleAmount: 2.0, division: "1"),
            Sale(saleAmount: 3.0, division: "2")
        ]
        salesGroupedByDivision = Dictionary(grouping: sales, by: { $0.division })

    }

    required init?(coder aDecoder: NSCoder) {
        fatalError()
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return salesGroupedByDivision.keys.count
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let division = Array(salesGroupedByDivision.keys)[section]
        return salesGroupedByDivision[division]?.count ?? 0
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        let division = Array(salesGroupedByDivision.keys)[indexPath.section]
        let sale = salesGroupedByDivision[division]?[indexPath.row]
        cell.textLabel?.text = "\(sale?.saleAmount)"
        return cell
    }

    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        let division = Array(salesGroupedByDivision.keys)[section]
        return "\(division) \(salesGroupedByDivision[division]?.reduce(0, { $0 + $1.saleAmount }) ?? 0)"
    }
}

let vc = VC()

PlaygroundPage.current.needsIndefiniteExecution = true
PlaygroundPage.current.liveView = vc

这篇关于在TableView中填充数组字典的高效清洁方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆