Swift Sort an array with multiple sort criteria

How is an array sorted by several criteria in Swift? For example, an array of dictionaries, as shown:

items = [
    [
        "item":"itemA"
        "status":"0"
        "category":"B"
    ],[
        "item":"itemB"
        "status":"1"
        "category":"C"
    ],[
        "item":"itemC"
        "status":"0"
        "category":"A"
    ],[
        "item":"itemD"
        "status":"2"
        "category":"A"
    ]
]

This should be sorted as follows:

  • ASC category
  • DESC status

I have successfully sorted this array based on any 1 OR 2 condition, but not both. Below is the code for this:

itemArray.sort({
        $0["category"] < $1["category"])
    })

How can this be expanded to include several sorting criteria in a given order?

+4
source share
1 answer

You want to use lexicographic comparison, that is, if the first fields are equal, compare the second field, otherwise compare the first fields.

, , , , == < .

let result = items.sorted {
    switch ($0["category"],$1["category"]) {
    // if neither "category" is nil and contents are equal,
    case let (lhs,rhs) where lhs == rhs:
        // compare "status" (> because DESC order)
        return $0["status"] > $1["status"]
    // else just compare "category" using <
    case let (lhs, rhs):
        return lhs < rhs
    }
}

a lexicographicCompare, , , a) , <, Comparable, nils b) .

+11

Source: https://habr.com/ru/post/1568570/


All Articles