快速筛选对象数组中包含的相同位置坐标 [英] Swift Filter same location coordinates contained inside an array of objects
问题描述
我从服务器接收到一系列对象中的存储信息列表.下面是一个示例-
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
]
}]
我正在尝试什么?: 我需要过滤出具有相同latLng值的数组中的商店.
What am I trying?: I need to filter out the stores in the array that has same latLng values.
为什么? 我需要识别这些相同的latLng"值,并向纬度值添加0.001之类的某个值的偏移量,以便在地图上显示这些商店时,位于同一位置的商店会并排出现.
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.
我发现了这一点(通过 Rob B )作为该方法的参考.
I found this (answer by Rob B) as reference for this approach.
我需要什么?
1.如何过滤数组中对象内部的值?
我在for循环中尝试过类似的方法-
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 :-(
- 过滤并添加相同值的偏移量后,如何使用这些更新后的值更新数组?
推荐答案
以下方法在适当的地方修改了每个商店的纬度,使其与另一个商店的纬度相匹配:
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
}
}
仅需一小段建议:不要将经纬度值存储在数组中.为它们创建一个struct/class或使用元组存储它们.
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.
这篇关于快速筛选对象数组中包含的相同位置坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!