ios - 在 TableView 中填充数组字典的高效且干净的方法

标签 ios arrays swift uitableview dictionary

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

class Sale  {

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

我收到数据并存储在

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

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

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

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]
    }

最佳答案

试试这个 Playground :

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

关于ios - 在 TableView 中填充数组字典的高效且干净的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53373155/

相关文章:

iphone - 在 iphone iOS SDK 中升级我的 safari 浏览器

ios - 按返回键 "without"关闭软件键盘 - SwiftUI

ios - 使用 Swift 在 Firebase 数据库中将一个 child 添加到一个 child

ios - 添加CocoonJS iOS WebView +插件后,iOS PhoneGap插件停止工作

iOS : How to detect any key pressed when use a BT keyboard

iOS 和 XCode : Issue with certificates

javascript - 使用 JavaScript 从多维数组创建 HTML

c++ - 在对字符串进行排序时在 C++ 中使用 sort()

angularjs - 我怎样才能用 ng-repeat 制作这个过滤器

iOS Swift 4 - 如何将数据传递给 splitviewcontrollers master