如何在表视图中查找重复项并显示计数

时间:2019-04-16 04:41:27

标签: ios arrays swift xcode uitextfield

我有一个类似的数组列表,我需要在表视图中显示

let data = ["a", "a", "b", "c"]

在表格视图中,我需要在每一行中显示所有字符串。我做到了。但是我需要找到重复项并需要更新计数,例如说。在我的数组中,我有a作为2 counts

所以在我的表格视图中,我需要显示为

a(2)
b
c

任何帮助将不胜感激。谢谢

2 个答案:

答案 0 :(得分:1)

class TableVC: UIViewController {

    //MARK: - Outlet & Properties
    let data = ["a", "a", "b", "c"]
    var unique = [String]()

    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()


        // Do any additional setup after loading the view.
        tableView.dataSource = self
        unique = Array(Set(data)) // Here you will get Unique Elements of Array
    }

}

//MARK: - UITableView datasource
extension TableVC : UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return unique.count
    }

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

        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! tableCell
        cell.label.text = unique[indexPath.row] + " " +  String(data.filter{$0 == unique[indexPath.row]}.count)

        print(data.filter{$0 == unique[indexPath.row]}.count) // Here you will get COUNT of an Element.
        return cell
    }
}

答案 1 :(得分:0)

UITableView不会为您做任何魔术。您应该只创建一个对您所显示内容有意义的数据构造器。在您的情况下,只需将数据构造函数转换为对您显示的内容更有意义的内容。将其从字符串数组更改为具有每个行中需要的所有信息的对象数组。我不确定您是否真的只显示“ a(2)”,我怀疑您已简化了问题。您可能需要类似的东西:

class ObjectThatRepresentsOneRowOfTheTable {
    var subObjects:[String] = []
    var title:String?
}

此数据构造函数还使您可以访问合并在一起的对象,如果它们不仅仅是相同的字符串,则将很有用。

您遍历数组并将这些对象组合在一起,成为代表表的一行的容器对象。显然,使用适合您特定问题的更好的名称。