检查复杂多维字典中是否存在键

Checking If Key Exists in Complex Multidimensional Dictionary

我将用户的位置和分配给他们的项目存储在不同的表中。认为它是因为有用户正在销售的商品,并且商品的位置已分配给用户。

我正在使用 radius 来检索用户的位置。如果我使用 10 公里半径,我可以检索所有项目。但是,我想把项目分开到每公里,比如:

- 1km
  - Guitar
  - Sofa
- 2km 
  - Citroen
  - Renault
  - Piano

问题是查询是这样工作的,所以如果我使用“10km”作为半径,它会获取从 0 到 10km 的所有内容:

let circleQuery = geoFire.queryAtLocation(center, withRadius: 10)

所以它记录如下:

- 1km
  - Guitar
  - Sofa
- 2km 
  - Guitar
  - Sofa
  - Citroen
  - Renault
  - Piano

我认为一种方法是使用 for 循环并将其存储到字典中。

我尝试的方法:

var items = [Int: AnyObject]()

func retrieveItems() {

  let center = CLLocation(latitude: userLatitude, longitude: userLongitude)

    for index in 1...25 {
        let circleQuery = geoFire.queryAtLocation(center, withRadius: Double(index))

       // after everything fetched

       self.items = [
           index : [itemId : value]
       ]

      // So, 'index' would be km 
      // 'itemId' is the id in db
      // 'value' would be 'key: value'

      // the database table looks like:
      //   - itemId:
      //      key:value
      //      key:value
    }
  }

示例字典树:

 let dictionary = [
    1 : [
        "item1" : ["key": "value", "key": "value"],
        "item2" : ["key": "val", "key": "val"],
        ],
    2 : [
        "item3" : ["key": "val", "key": "val"],
        "item4" : ["key": "val", "key": "val"],
        "item5" : ["key": "val", "key": "val"],
    ]
]

每次索引增加时,它都是从 0km 开始获取的,所以它是重新获取已经获取的东西。但是,使用字典,也许我可以检查一下,如果 'itemId' 已经在字典中,请不要重新添加它。

我的问题是,有没有一种方法可以检查 'itemId' 是否已经使用上述方法添加到字典中,所以我不添加已经添加的项目?在像上面这样的复杂的多维字典中实现它的方法是什么?


更新:我试过类似的方法来检查 "itemId" 是否存在

     if self.events.indexForKey(index) != nil {
         let radius = self.events[index]! as! Dictionary<String, AnyObject>
         print("km exists")
     } else {
         print("distance doesn't exist")
         self.items = [
             index : [itemId : value]
           ]            
     }

但它总是进入 else 位。

如果您不想获得重复的事件,您应该只在 25 公里处进行一次查询,检索所有密钥,然后使用客户端逻辑将它们过滤到单独的公里组中。您可以计算返回的键坐标与查询中心之间的距离 using some math.