Swift Filter same location coordinates contained inside an array of objects

旧巷老猫 提交于 2019-12-13 07:32:06

问题


I am receiving from Server, a list of Stores information in an array of objects. Below is a sample -

"stores": [
    {            
        "name": “Store 1”,
        "number": "5381",           
        "country": "BELGIE",
        "latLng": [
            50.730614,
            4.231847
        ]

    },
    {            
        "name": "Store 2”,
        "number": "5220",            
        "country": "BELGIE",
        "latLng": [
            50.730614,
            4.231847
        ]

    },
    {            
        "name": "Store 3”,
        "number": "3982”,           
        "country": "BELGIE",
        "latLng": [
            50.7315706,
            4.2303477
        ]

    },
    {           
        "name": "Store 4”,
        "number": "4179",            
        "country": "BELGIE",
        "latLng": [
            50.7262577,
            4.245589
        ]           
    }]

What am I trying?: I need to filter out the stores in the array that has same latLng values.

Why? I need to identify these 'same latLng' values and add an offset of some value like 0.001 to the latitude value so that when I show these stores on a map, the stores on same location appear side by side.

I found this (answer by Rob B) as reference for this approach.

What I need?
1. How can I filter with values inside of an object in the array? I tried something like this inside a for loop -

print("\(allStoresInfo.filter({ $0.latLng![0] == $0.latLng![0] }).count)")

This value always returns 4. I know I am missing some basic sense here but need know what it is :-(
  1. After I filter and add the offset for same values, how do I update my array with these updated values?

回答1:


The following method modifies in place the latitude of each store that matches the latitude of another store:

allStoresInfo.map{ currentStore in allStoresInfo.filter{$0.latLng![0] == currentStore.latLng![0]}.enumerated().forEach{ index, matchingStore in
        matchingStore.latLng![0] += Double(index)*0.001
    }
}

Just a small piece of advice: don't store lat-long values in an array. Either create a struct/class for them or use a tuple to store them.



来源:https://stackoverflow.com/questions/45588085/swift-filter-same-location-coordinates-contained-inside-an-array-of-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!