1

What is the best practice of sorting this table in Swift 4?
A-Z

    override func viewDidLoad() {

        super.viewDidLoad()

        list = [ ghost(name:"alphabet".localized, id:"1"),
             ghost(name:"élephant".localized, id:"2"),
             ghost(name:"delegate".localized, id:"3")]
    }

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

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if filtering() { 
            return filter.count 
        }
        return list.count 
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "library", for: indexPath)
        var data: ghost

        if filtering() { 
            data = filter[indexPath.row] 
        }
        else { 
            data = list[indexPath.row] 
        }

        cell.textLabel!.text = data.name
        return cell 
    }

I am using translated strings a lot. So it would be nice, if the table can be loaded alphabetically in different language. Can someone help me with that? I searched the whole internet and just got too exhausted of this... Thanks a lot!

Tomáš Pánik
  • 556
  • 1
  • 5
  • 18

1 Answers1

2

You can use it as follows:

func sortAlpha() {

    if filtering() {
        filter.sort { (item1, item2) -> Bool in
            return item1.name > item2.name
        }
    }
    else {
        list.sort { (item1, item2) -> Bool in
            return item1.name > item2.name
        }
    }
    self.tableView.reloadData()
}

then just call sortAlpha()

Miknash
  • 7,888
  • 3
  • 34
  • 46
  • 1
    then just call sortAlpha() when you got the list, before reload data. Where are you trying to sort it anyway? – Miknash Aug 01 '18 at 14:18
  • "alphabet".localized should return string at the end - in viewDidLoad what happens if you call sortAlpha? – Miknash Aug 01 '18 at 14:24
  • you are awesome :) it's working. but now I've got Z-A and I am using some characters like á é and so on, these are on top of the table; then Z ..... A – Tomáš Pánik Aug 01 '18 at 14:28
  • You can try things like ascii encoding string and then sort or look for another solution for special characters sort – Miknash Aug 01 '18 at 14:36
  • 1
    something like https://stackoverflow.com/questions/45277831/the-array-value-should-be-sort-like-alphabetic-numbers-and-special-characters should work. if you use some other function for sorting you can create it as bool and return its result instead of item1.name > item2.name. e.g. return mySortFunc() – Miknash Aug 01 '18 at 14:39
  • oh c'mon I was just editing code formatting while the website told me you had more recent edit on it -.- I don't like downvotes :D – Tomáš Pánik Aug 01 '18 at 14:44