ios - 附加多维字典

标签 ios swift dictionary multidimensional-array anyobject

我有一个多维字典,我试图向其中添加数据而不删除数据,但如果重复则覆盖。

var items = [Int: AnyObject]()

var IdsAndDetails = [String:AnyObject]()
let index = 3 // static for test

...
for result in results {
     // result is String (result also indicates itemId)

     let details = self.IdsAndDetails[result]  
     // details is AnyObject like [String:String]

    if let itemDetails = details {        
         // Here I want to append data into 'items' variable

         // This doesn't work: (Error-1)
          self.items[index]![result] = itemDetails

    }

(错误1):

Cannot assign to immutable expression to type AnyObject.


但是,如果我尝试这样做,它会起作用,但这不是我想要的方法。它正在重新创建字典。相反,我想附加数据。

      self.items = [
         index : [result : itemDetails]
      ]

我最终想要得到的字典结构是:

items = [
    index : [
        "id1" : ["key": "value", "key": "value"],
        "id2" : ["key": "val", "key": "val"],
        ],
    index : [
        "id3" : ["key": "val", "key": "val"],
        "id4" : ["key": "val", "key": "val"],
        "id5" : ["key": "val", "key": "val"],
    ]
]

// index is Integer
// [Key:Value] is [String:String] - itemDetails equal to all `[key:value]`s
// 'id' is also String

更新:我也尝试过,但没有运气

     let a = self.items[index]
     a![result]! = itemDetails as [String:String]

更新2:

    let valueDict = (value as! NSDictionary) as Dictionary

    for (key, val) in valueDict {
        let keyString = key as! String
        let valString = val as! String

        self.items[index]![result]![keyString]! = valString
    }

但它抛出错误:

fatal error: unexpectedly found nil while unwrapping an Optional value

但令人惊讶的是调试显示了所有值:

po index : 1
po itemId : "123123"
po keyString: "keyInString"
po valString: "valInString"

更新 3:

 for index in 1...5 {
   var results = [String]()

   // First I retrieve nearby users and assign it to key

   let itemsRef = Firebase(url: self.secret + "/items")
   eventsRef.queryOrderedByChild("user_id").queryEqualToValue(key).observeEventType(.ChildAdded, withBlock: { snapshot in
   // ^ above 'key' is the user_id retrieved before

   let itemDetails = snapshot.value // item details - [key:val, key:val]
   let itemId = snapshot.key        // item ids [id1,id2,id3]

   // I used 'KeyAndDetails' to store all values with ids 
   let IdsAndDetails = [itemId: itemDetails]

   self.itemIdsArray = []
   self.itemIdsArray.append(itemId)

   if index == 1 {
       // self.items = [
       //    index : [itemId : itemDetails]
       // ]
       // ^ This worked and gave me the structure
       // but I don't want to overwrite it, instead, I want to append
       // on the dictionary

       // This is where I am trying to append into `self.items`,
       // and throws error:
       self.items[index]?[result] = (eventDetails as! [String : String])
   }
  ...

最佳答案

看起来您正在尝试绕过 Swift 的类型系统而不是使用它。而不是使用 AnyObject ,您应该尝试使用您想要的该字典值的确切类型。在本例中,您似乎想要类似 [Int: [String: [String: String]]] 的内容。 (尽管,就像 @EricD 在评论中所说,如果可能的话,您可能应该使用结构体)

这是一个与您问题中的代码类似的快速(静态)示例:

var items = [Int: [String: [String: String]]]()
let idsAndDetails = ["id2": ["key3": "value3"]]

let index = 3
items[index] = ["id1": ["key1": "value1", "key2": "value2"]]

let result = "id2"
if let itemDetails = idsAndDetails[result] {
    items[index]?[result] = itemDetails
}

最后,items将是:

[3: ["id1": ["key1": "value1", "key2": "value2"], "id2": ["key3": "value3"]]]

?items[index]?[result]告诉 Swift 确保 items[index]在尝试执行下标方法之前为非零。这样,如果您尝试更新 index items 中不存在你不会导致崩溃。

关于ios - 附加多维字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37424640/

相关文章:

ios - 使用 Parse.com iOS 搜索用户名以获取用户

ios - Swift 将新的堆栈 View 添加到现有堆栈 View

c++ - 在我的 STL 容器映射中找不到特定键

python - 字典排序和删除

ios - 在后台模式下关闭我的应用程序后将下载简历

ios - 有没有办法获取我的 iOS 应用程序屏幕截图列表?

带有32位第三方库的iOS arm64项目

swift - 如何通过 Action 将物体向上移动?

ios - 如何在 Swift 中对 Json 字典数组值进行排序(A-z、0-9 和特殊字符)

python list to dict转换困惑