How to sort a dictionary by an array value contained in the dictionary Swift -
i have dictionary contains arrays elements , want sort 1 of array values. solutions found sorting dictionaries single elements , not arrays. also, didn't understand $0.0 meant? below code example of i'm trying accomplish.
var dict = ["mike": [62, 160], "jim": [72, 210], "tony": [68, 187]] //i want sort height (array values [0]) highest value lowest. //the output this: "jim": [72, 210] "tony": [68,187] "mike": [62,160]
i'm relatively new coding have no idea how approach this.
see, have dictionary sorted:
let dict = ["mike": [62, 160], "jim": [72, 210], "tony": [68, 187]]
you want sort function isorderedbefore: (self.generator.element, self.generator.element) -> bool
if first 1 element should have been higher second one, should put a > b
function , on.
let sorteddict = dict.sort { (first: (string, array<int>), second: (string, array<int>)) -> bool in return first.1[0] > second.1[0] }
it's 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 function's variable has number 0 , on. $0.0
means got first dictionary field (in case it's name), while $0.1
means it's second dictionary field (an array).
Comments
Post a Comment