How to sort array of custom objects by customised status value in swift 3?
arrays, object, sorting, swift3
Solution
You have to provide a value that will yield the appropriate ordering when compared in the sort function.
For example:
extension orderFile
{
var statusSortOrder: Int
{ return ["open","confirmed","closed","cancelled"].index(of: status) ?? 0 }
}
let sortedOrders = aOrders.sorted{$0.statusSortOrder < $1. statusSortOrder}
Problem
lets say we have a custom class named orderFile and this class contains three properties. ``` class orderFile { var name = String() var id = Int() var status = String() } ``` a lot of them stored into an array ``` var aOrders : Array = [] var aOrder = orderFile() aOrder.name = "Order 1" aOrder.id = 101 aOrder.status = "closed" aOrders.append(aOrder) var aOrder = orderFile() aOrder.name = "Order 2" aOrder.id = 101 aOrder.status = "open" aOrders.append(aOrder) var aOrder = orderFile() aOrder.name = "Order 2" aOrder.id = 101 aOrder.status = "cancelled" aOrders.append(aOrder) var aOrder = orderFile() aOrder.name = "Order 2" aOrder.id = 101 aOrder.status = "confirmed" aOrders.append(aOrder) ``` Question is: How will I sort them based on status according to open, confirm, close and cancelled?