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  }
0

2 Answers 2

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"]) }
Sign up to request clarification or add additional context in comments.

1 Comment

I like this implementation better than mine. I ended up creating a function to do the "translation" to a numeric value.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.