abuessing
abuessing

Reputation: 35

How to sort a dictionary by an array value contained in the dictionary Swift

I have a dictionary that contains arrays as its elements and I want to sort by one of the array values. All the solutions I found for sorting dictionaries where for single elements and not arrays. Also, I didn't understand what $0.0 meant? Below is a code example of what I'm trying to accomplish.

var dict = ["Mike": [62, 160], "Jim": [72, 210], "Tony": [68, 187]]

//I want to sort by the height (array values [0]) from highest value to lowest.
//The output would look like this:

"Jim": [72, 210]
"Tony": [68,187]
"Mike": [62,160]

I'm relatively new to coding so I really have no idea how to approach this.

Upvotes: 3

Views: 150

Answers (2)

Beraliv
Beraliv

Reputation: 564

See, you have dictionary to be sorted:

let dict = ["Mike": [62, 160], "Jim": [72, 210], "Tony": [68, 187]]

You want to sort it with some function isOrderedBefore: (Self.Generator.Element, Self.Generator.Element) -> Bool so if the first one element should have been higher than the second one, you should put a > b into the function and so on.

let sortedDict = dict.sort { (first: (String, Array<Int>), second: (String, Array<Int>)) -> Bool in
    return first.1[0] > second.1[0]
}

It's the same as:

let sortedDict = dict.sort {
    return $0.1[0] > $1.1[0]
}

Or:

let sortedDict = dict.sort { $0.1[0] > $1.1[0] }

$0 means that your function's variable has number 0 and so on. $0.0 means that you got the first dictionary field (in your case it's a name), while $0.1 means it's the second dictionary field (an array).

Upvotes: 2

Nat
Nat

Reputation: 12948

You should make an object (or struct if it suits the case more) with name and these two values. Then store all the objects inside an array and you'll be able to sort it anyway you'd like to.

class MyObject {

    let name: NSString!
    let aValue: Integer!
    let bValue: Integer!

    // MARK: - Memory Management

    init(name: NSString, aValue: Integer, bValue: Integer) {
        self.name = name
        self.aValue = aValue
        self.bValue = bValue
    }
}

Then somewhere else:

let myArray = // fetch, set the values using init method and sort it

Upvotes: 0

Related Questions