I have a data like this
"geoData": [
{
"lat": 50.26877,
"long": 19.034,
"msg": "TEST 3",
"geoRadius": 30.48,
"pri" : 1
},
{
"lat": 50.26877,
"long": 19.034,
"msg": "TEST 2",
"geoRadius": 30.48,
"pri" : 2
},
{
"lat": 50.26877,
"long": 10.034,
"msg": "TEST 1",
"geoRadius": 30.48,
"pri" : 1
}
{
"lat": 50.26877,
"long": 10.034,
"msg": "TEST 4",
"geoRadius": 30.48,
"pri" : 2
}
]
Now i want to have a result dictionary as group by latitude and longitude and sort by pri
I tried something like this
let result = Dictionary(grouping: geoNotifications,
by: { (geoNotification)->Bool in
return geoNotification.latitude && geoNotification.longitude })
But it doesn't work Can someone share the logic for the same?
In the code you have given, I assume geoNotifications is an array of struct/objects similar to the below code:
struct GeoNotification
{
var latitude: Double
var longitude: Double
var msg: String
var geoRadius: String
var pri: Int
init(dict: [String:Any])
{
self.latitude = dict["lat"] as! Double
self.longitude = dict["long"] as! Double
self.geoRadius = dict["geoRadius"] as! String
self.msg = dict["msg"] as! String
self.pri = dict["pri"] as! Int
}
}
Having an array of GeoNotification objects, we can achieve both of your requirements as:
1. Grouping using longitude
var dict = Dictionary(grouping: geoNotifications) { $0.longitude }
Result:
["10.034000000000001": [geoNotification1, geoNotification2] , "19.034": [geoNotification3, geoNotification4]]
2. Sorting with pri
for (key, value) in dict
{
dict[key] = value.sorted(by: { $0.pri < $1.pri })
}
In the above code, I've picked every key-value pair from the dict we got earlier and sorted the value(it's an array of GeoNotification objects) according to pri.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With