0

I need to sort an array of JSON objects.

but it is needs to be translated from a literal meaning to a numeric meaning.

for example

object["status"]

"New" = 1

"Open" = 2

"Closed" = 3

/// I need to translated in here some where

var sortedOrders = orders.sort { $0["status"].doubleValue < $1["status"].doubleValue  }
Arcadian
  • 4,312
  • 12
  • 64
  • 107

2 Answers2

1

You could do this with an enum.

enum Status: Int {
    case new = 1
    case open = 2
    case closed = 3
    case unknown = 99

    init(string: String) {
        switch string {
        case "new", "New": self = .new
        case "open", "Open": self = .open
        case "closed", "Closed": self = .closed
        default:
            self = .unknown
        }
    }
}

To use the enum, you could initialize like this:

var myStatus = Status(string: object["status"])

And use it like this:

print(myStatus) // prints "new"
print(myStatus.rawValue) // prints "1"

Edit: Since the enum has an underlying type of Int, to accomplish your sort you can compare the resulting Status directly (Thanks to this question https://stackoverflow.com/a/27871946/1718685):

var sortedOrders = orders.sort { Status(string: $0["status"]) < Status(string: $1["status"]) }
Stephen
  • 1,154
  • 11
  • 27
  • I like this implementation better than mine. I ended up creating a function to do the "translation" to a numeric value. – Arcadian Dec 20 '17 at 20:29
0

Here's one way:

let statuses = [ "New", "Open", "Closed" ]
var sortedOrders = orders.sort { (statuses.index(of: $0["status"] ?? "") ?? 99) < (statuses.index(of: $1["status"] ?? "") ?? 99) }

This will determine the index of each status within the statuses array. 99 will be used for unknown or missing statuses so any unknown statuses will appear at the end of the list.

rmaddy
  • 314,917
  • 42
  • 532
  • 579