ios - 尝试使用 swift 根据对象的公共(public)键拆分对象数组

标签 ios arrays dictionary swift

我完全迷失了 swift 。我正在尝试根据公共(public) key 拆分对象数组(使用 Parse SDK 检索)。 基本上我想做一个 COUNT + GROUP BY,但我找不到使用 Parse SDK 进行 GROUP BY 的方法,所以我尝试对对象进行分组并通过代码对它们进行计数。 但首先,我写的东西看起来很糟糕,其次,它甚至无法编译,我不明白为什么。

这是我正在使用的代码

var groupedEntries = [String: [String: AnyObject?]]()

...

let query = PFQuery(className: "Entry")
query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]!, error: NSError!) -> Void in
   if error == nil {

      var groupingKey: String
      for object in objects {

         groupingKey = object[groupingKey] as String
         if self.groupedEntries[groupingKey] != nil {
            self.groupedEntries[groupingKey]["count"] = self.groupedEntries[groupingKey]["count"] + 1
         } else {
            self.groupedEntries[groupingKey]["count"] = 1
         }
      }
      self.tableView.reloadData()
   }
}

并且编译器给出以下错误:“String”不可转换为“DictionaryIndex”。无论我尝试什么,我都会收到与可选或包装相关的错误。

感谢任何帮助我的人:)

最佳答案

当使用 subscript 时,Dictionary 返回给定值类型的可选值,因此您需要将其解包。您需要使用我使用的额外变量 somevar.见下面的代码

var groupedEntries = [String: [String: AnyObject?]]()

@IBAction func changeImage(sender: AnyObject){
    var objects:[AnyObject]!
    var groupingKey: String //= "abc" Intialize before using
    //var countryCode: String   //= "abc" not defined in your code

    for object in objects {

        groupingKey = object[groupingKey] as String
        if self.groupedEntries[groupingKey] != nil {
            var somevar = self.groupedEntries[groupingKey]!
            somevar["count"] = (somevar["count"]! as Int) + 1
        } else {
            self.groupedEntries[groupingKey] = ["count":1]
        }
    }
}

我不知道你的逻辑,但这段代码编译得很好。

关于ios - 尝试使用 swift 根据对象的公共(public)键拆分对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26192816/

相关文章:

ios - 为什么splitViewController :collapseSecondaryViewController:ontoPrimaryViewController: is not called on iPhone 6 Plus?

javascript - node.js 是否提供真正的数组实现?

json - 如何使用 JSON 中的嵌套类型在 Swift 中表示字典

loops - 如何在范围循环中添加到 map 中

android - 本地移动应用程序的实时服务器更新

ios - 没有ImageView时如何将 View 向上移动?

ios - 显示没有导航 View Controller 的后退按钮

php - 如何使用 PHP 从 MySQL 数据库生成整个数据库表的 JSON 数组

python - 将多个构建的 BOM(零件列表)保存到 Python 中的文件中

dictionary - 崇高的文本 3 : Remove a mis-spelled word the dictionary