Ivan Kisin
Ivan Kisin

Reputation: 385

How to sort cells in tableView?

How to sort cells in tableView?


I have struct and array:

struct Converter {
        let title: String
        let kf: Double
    }

    let converterAtmo = [
        Converter(title: "Атмосферы", kf: 1),
        Converter(title: "Бары", kf: 365.2422),
        Converter(title: "Мм.рт.ст.", kf: 11.999998),
        Converter(title: "Паскали", kf: 525948.77),
        Converter(title: "Фунт./кв.дюйм", kf: 52.177457)]

in CellAtRow func:

let cell1 = tableView.dequeueReusableCell(withIdentifier: "resultCell") as! resultTableViewCell

            let item = converterAtmo[indexPath.row]

            cell1.nameResult.text = item.title
            cell1.labelResult.text = String(item.kf * atmosfera)


            return cell1

And finally @IBAction:

 @IBAction func sortAlphabet(_ sender: Any) {

        let itemSort = converterAtmo

        itemSort.sorted { $0.title < $1.title }

        self.tableView2.reloadData()

    }

But it's not working...

What is my problem?

Upvotes: 0

Views: 4020

Answers (2)

Milan Nos&#225;ľ
Milan Nos&#225;ľ

Reputation: 19737

First, you have to declare converterAtmo as var instead of let so that you can modify it.

Then replace:

itemSort.sorted { $0.title < $1.title }

with:

self.converterAtmo = itemSort.sorted { $0.title < $1.title }

In your current implementation you sort a copy of your model (itemSort is just a copy of your self.converterAtmo), so it does not have any effect on the model behind the tableView. You need to set that sorted array back to tableView data model.

Or even better, you can just use this:

@IBAction func sortAlphabet(_ sender: Any) {
    // `sort` method will sort the converterAtmo (`sorted` method leaves the original 
    // array untouched and returns a sorted copy)
    self.converterAtmo.sort { $0.title < $1.title }
    self.tableView2.reloadData()
}

Upvotes: 6

Jay
Jay

Reputation: 91

In :

let itemSort = converterAtmo
itemSort.sorted { $0.title < $1.title }

You are not actually sorting your array. You are copying it in 'itemSort' and not doing anything with it.

Upvotes: 0

Related Questions