Sort Arrays

Hi!

Some help, please!!!


I want to sort my list on tableView by carDate, typeCar or carColor. But is the problem when I sort only array, the others arrays won't will be sorted and will be shuffle.


var carDate = [String]()

var typeCar = [String]()

var carColor = [String]()

var carImage = [UIImage]()


That's all loading on my tableView.


cell.myDateCar.text? = dateCar[indexPath.row]...

cell.myTypeCar.text? = typeCar[indexPath.row]...

...

return cell



And the feature to Sorting out:


//action sheet

let refreshAlert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)


refreshAlert.addAction(UIAlertAction(title: "Sort by Date", style: .default, handler: {

(action: UIAlertAction!) in


carDate.sort()

self.myTableView.reloadData()


//and my Logic on cellForRowAt: _


}))


refreshAlert.addAction(UIAlertAction(title: "Sort by Type", style: .default, handler: {

(action: UIAlertAction!) in



}))


refreshAlert.addAction(UIAlertAction(title: "Sort by Color", style: .default, handler: {

(action: UIAlertAction!) in



}))



refreshAlert.addAction(UIAlertAction(title: "Default", style: .default, handler: {

(action: UIAlertAction!) in


}))



refreshAlert.addAction(UIAlertAction(title: "Cancelar", style: .cancel, handler: { (action: UIAlertAction!) in

return

}))


}



This works very well to sort array. But only one array will be sorted and the others not will be sorted.

Some tip or some help? I have been trying to get one array to all atributes buts is confuse.

Sorry if this doubt is too simple but I'm trying to find way.


The problem: Some car like BWM have White color and other car like a Corvet have a black color. I can't sort all things.

I need to sort Colors and keep the atributes like the name of the car without shuffle.


Thank you.

Replies

Build a model object with all sortable properties in it


struct Car : Equatable {
    let date : Date // You probably should use 'Date' instead of a String
    let type : String
    let color : String
}


Then, you can sort them on different criteria. Example:

let cars = [Car(date: Date(), type: "One", color: "Blue"), Car(date: Date(), type: "Two", color: "Aqua")]

let sortedCars = cars.sorted {
  $0.color < $1.color
}


Note: I left out the image property in this example. You can add that in later. Perhaps maybe have that property be a String to store an image name instead.


The above code returns a new array. If you want to sort the original array, make it a 'var' and then use 'sort(by:)' instead of 'sorted(by:)'

Thank you so much!! I’ll try following yours steps!!