Search code examples
swiftsortingcase-insensitive

How to make a sort case insensitive


My application reads a Firebase DB with several companies and load them to a TableView. My code is

class TableViewController: UITableViewController {

    var clinics: [Clinic] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        ProgressHUD.show("Loading...")

        let database = Database.database().reference()
        let clinics = database.child("clinics")

        // Clinics listeners
        clinics.observe(DataEventType.childAdded) { (snapshot) in
            let dados = snapshot.value as? NSDictionary
            let clinic = Clinic()
            clinic.id = snapshot.key
            clinica.name = dados?["name"] as! String

            self.clinics.append(clinic)

            // Sorting
            self.clinicas.sort(by: { $0.nome < $1.nome })

            self.tableView.reloadData()
            ProgressHUD.dismiss()
        }

        clinics.observe(DataEventType.childRemoved) { (snapshot) in
            var index = 0
            for clinic in self.clinics {
                if clinic.id == snapshot.key {
                    self.clinics.remove(at: index)
                }
                index = index + 1
            }
            self.tableView.reloadData()
            ProgressHUD.dismiss()
        }
    }
 }

Clinics structure is

class Clinica {
    var id = ""
    var name = ""
}

That code works perfectly fine and all clinics are added to my TableView.

The thing that is not working as I expected is the Sort... The line below kind of do the sort but is Case Dependant. I'm trying to Sort by Name and Case Insensitive. I've done a lot of research here but I couldn't really find anything that would do it.

Is there a way to sort by name and be case insensitive?

Thanks


Solution

  • Assuming that the nome property is a String, you can use compare(:options:):

    self.clinicas.sort {
        $0.nome.compare($1.nome, options: .caseInsensitive) == .orderedAscending
    }