4

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?

3 Answers3

9

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}
Alain T.
  • 40,517
  • 4
  • 31
  • 51
2

In your code you should make an array to store each aOrder with aOrders.append(aOrder) at each aOrder defination.

Then sort it with below code, refor this for more.

aOrders.sorted({ $0.status > $1.status })
Community
  • 1
  • 1
LF00
  • 27,015
  • 29
  • 156
  • 295
0

The answer for swift 3 is as following

Ascending:

aOrders = aOrders.sorted(by: 
                 {(first: orderFile, second: orderFile) -> Bool in
                   first.status > second.status
                 }
              )

Descending:

aOrders = aOrders.sorted(by: 
                 {(first: orderFile, second: orderFile) -> Bool in
                   first.status < second.status
                 }
              )