ios - 检查键是否存在于复杂的多维字典中

标签 ios swift dictionary nsdictionary

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

我正在使用 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 公里处进行一次查询,检索所有 key ,然后使用客户端逻辑将它们过滤到单独的公里组中。您可以计算返回的键坐标与查询中心之间的距离 using some math .

关于ios - 检查键是否存在于复杂的多维字典中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37380139/

相关文章:

JavaScript - 用两根或更多手指滚动

ios - 从代码添加子 UIViewController 时显示警告

string - 我有一个向量,例如 (1,2,3,4),我想将数字更改为字符串

python : List + lambda behaviour

ios - UICollectionView + AFNetworking + 自动滚动/分页?

c++ - 将 'upserting' 项放入 map<key, shared_ptr<foo>> 的正确方法

ios - 如何通过快速按下标签来显示/隐藏标签?

iphone - iPhone 中的 JSON 响应第二次为空

swift - iap 收据验证 : security

Xcode 6 Swift 在文本字段中将字符串转换为 Int