-1

I have an list of array like and I needs to show in table view

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

In my table view, I need to show all the string in each row. That i done.But i need to find the duplicate and needs to update the count like say. In my array i have a as 2 counts.

So in my table view I needs to show like

a(2)
b
c

Any help will be highly appreciated. Thanks

dahiya_boy
  • 9,298
  • 1
  • 30
  • 51
drangon
  • 21
  • 5

1 Answers1

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
    }
}
Ahtazaz
  • 903
  • 8
  • 21