Swift Dictionary Sort by Object Value
I have a dictionary like <String,Loto>
and Loto is an object as shown below;
Loto:
{
"success": true,
"data": {
"oid": "64kbbqi8dbxygb00",
"hafta": 961,
"buyukIkramiyeKazananIl": "",
"cekilisTarihi": "11/04/2015",
"cekilisTuru": "SAYISAL_LOTO",
"rakamlar": "03#02#48#16#15#08",
"rakamlarNumaraSirasi": "02 - 03 - 08 - 15 - 16 - 48",
"devretti": false,
"devirSayisi": 0,
"bilenKisiler": [
{
"oid": "64kbbxi8dbxyg403",
"kisiBasinaDusenIkramiye": 7.35,
"kisiSayisi": 185712,
"tur": "$3_BILEN"
},
{
"oid": "64kbbxi8dbxyg402",
"kisiBasinaDusenIkramiye": 53.05,
"kisiSayisi": 9146,
"tur": "$4_BILEN"
},
{
"oid": "64kbbxi8dbxyg401",
"kisiBasinaDusenIkramiye": 4532.2,
"kisiSayisi": 142,
"tur": "$5_BILEN"
},
{
"oid": "64kbbxi8dbxyg400",
"kisiBasinaDusenIkramiye": 1528438.75,
"kisiSayisi": 1,
"tur": "$6_BILEN"
}
],
"buyukIkrKazananIlIlceler": [
{
"il": "10",
"ilView": "BALIKESÄ°R",
"ilce": "01001",
"ilceView": "AYVALIK"
}
],
"kibrisHasilati": 51127,
"devirTutari": 0.09,
"kolonSayisi": 10537872,
"kdv": 1599672.97,
"toplamHasilat": 10537872,
"hasilat": 8938199.03,
"sov": 893819.9,
"ikramiyeEH": 8044379.129999999,
"buyukIkramiye": 1528432.03,
"haftayaDevredenTutar": 0
}
}
So my dictionary is like <"11042015", Loto> and I want to sort this dictionary using the "hafta" property of the loto object.
How can i do this? Please help me!
source to share
If Loto
is an object with a property hafta
, you can sort the dictionary by passing it to a function sorted
, as well as a closure that says how to order the entries:
sorted(dict) { $0.1.hafta < $1.1.hafta }
( $0.1
and $1.1
, because dictionaries are a sequence of key / value pairs - you want to sort by value property, i.e. tuple insertions 1
)
Note, this will return you a sorted array of type [(String,Loto)]
, not a dictionary (since Swift dictionaries are unordered).
(if Loto
not actually an object, but rather another dictionary, you may need to do {$0.1["hafta"] < $1.1["hafta"]}
- it really depends on how you keep your data - good news: you don't have to worry about additional options as they can be compared to <
)
If you don't need keys, just sort the values:
sorted(dict.values) { $0.hafta < $1.hafta }
which will return you a sorted array like [Loto]
source to share