追加多维字典

Appending Multidimensional Dictionary

我有一个多维字典,我想在不删除数据的情况下向其中添加数据,但如果重复则覆盖。

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]

更新二:

    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] 不为零。这样,如果您尝试更新 items 中不存在的 index,则不会导致崩溃。