【问题标题】:How to append elements into a dictionary in Swift?如何在 Swift 中将元素附加到字典中?
【发布时间】:2015-02-03 11:12:22
【问题描述】:

我有一个简单的字典,其定义如下:

var dict : NSDictionary = [ 1 : "abc", 2 : "cde"]

现在我想在这个字典中添加一个元素:3 : "efg"

如何将3 : "efg" 追加到现有字典中?

【问题讨论】:

  • 使用 NSMutableDictionary
  • 您确定要字典而不是数组,因为您的键似乎是数字 1、2 和 3?

标签: swift nsdictionary


【解决方案1】:

您正在使用NSDictionary。除非您出于某种原因明确需要它是那种类型,否则我建议使用 Swift 字典。

您可以将 Swift 字典传递给任何期望 NSDictionary 的函数,而无需任何额外工作,因为 Dictionary<>NSDictionary 可以无缝地相互连接。原生 Swift 方式的优点是字典使用泛型类型,所以如果你定义它以Int 为键,String 为值,就不会误用不同类型的键和值。 (编译器会代表您检查类型。)

根据我在您的代码中看到的内容,您的字典使用 Int 作为键,String 作为值。要创建实例并稍后添加项目,您可以使用以下代码:

var dict = [1: "abc", 2: "cde"] // dict is of type Dictionary<Int, String>
dict[3] = "efg"

如果您稍后需要将其分配给NSDictionary 类型的变量,只需进行显式转换:

let nsDict = dict as! NSDictionary

而且,如前所述,如果您想将其传递给期望 NSDictionary 的函数,请按原样传递,无需任何转换或转换。

【讨论】:

  • 感谢您对一个人实际应该做什么的正确解释。利用 Swift 的便利性来创建和操作 Dictionary 对象,然后在需要时将其转换为 NSDictionary。精彩的。谢谢。
  • 无论如何我可以使用分隔符附加到同一个键(类似于addValue)。我的意思是像添加一个"Antonio"到键1所以dic[1]会返回"abc, Antonio"
  • @honey 不是我知道的......但如果元素已经存在,它是一个简单的附加
【解决方案2】:

您可以使用以下方式添加并将Dictionary更改为NSMutableDictionary

dict["key"] = "value"

【讨论】:

  • 我收到一条错误消息,上面写着Cannot assign to the result of this expression
  • 为您的问题添加这种方式 dict[3] = "efg";
  • 检查我编辑的答案它对我有用。将字典更改为可变的它可以工作!
  • dict["testval"] = "test".. 错误fatal error: unexpectedly found nil while unwrapping an Optional value
  • 它不适用于 2.2+ , dict 在该表达式中是只读的
【解决方案3】:

我知道这可能会很晚,但它可能对某人有用。 因此,要快速将键值对附加到字典中,您可以使用 updateValue(value: , forKey: ) 方法,如下所示:

var dict = [ 1 : "abc", 2 : "cde"]
dict.updateValue("efg", forKey: 3)
print(dict)

【讨论】:

  • 谢谢!当我尝试向字典添加新值时,我不断得到一些关于缺少默认参数的信息。这个方法奏效了。
【解决方案4】:

SWIFT 3 - XCODE 8.1

var dictionary =  [Int:String]() 

dictionary.updateValue(value: "Hola", forKey: 1)
dictionary.updateValue(value: "Hello", forKey: 2)
dictionary.updateValue(value: "Aloha", forKey: 3)

所以,您的字典包含:

字典[1: Hola, 2: Hello, 3: Aloha]

【讨论】:

  • 这比dictionary[1] = "Hola"好多少?
  • 只是另一种方法。一切都取决于你需要做什么!我的情况,这是最好的方法
  • 我了解您认为这样更好;这就是你发布它的原因。但我看不出这有什么更好的。请告诉我这样更好
  • 我同意应该有一个名为“addValue”或“setValue”的方法,正如它的名字所说,“updateValue”应该用于更新
  • 原因是字典初始化时的值 [] 与 nil 不同,因此必须使用属性 updateValue 因为我们正在尝试更改值而不是插入它。跨度>
【解决方案5】:

如果您的字典是 IntString,您可以这样做:

dict[3] = "efg"

如果您的意思是向字典的 value 添加元素,则可能的解决方案是:

var dict = Dictionary<String, Array<Int>>()

dict["key"]! += [1]
dict["key"]!.append(1)
dict["key"]?.append(1)

【讨论】:

    【解决方案6】:

    Swift 3+

    为 Dictionary 分配新值的示例。您需要将其声明为 NSMutableDictionary:

    var myDictionary: NSMutableDictionary = [:]
    let newValue = 1
    myDictionary["newKey"] = newValue
    print(myDictionary)
    

    【讨论】:

      【解决方案7】:

      在 Swift 中,如果你使用 NSDictionary,你可以使用setValue:

      dict.setValue("value", forKey: "key")
      

      【讨论】:

      • 编辑了您的答案,以后考虑添加更多信息以避免被否决。
      【解决方案8】:

      Dict.updateValue 从字典中更新现有键的值,如果键不存在,则添加新的新键值对。

      例子-

      var caseStatusParams: [String: AnyObject] = ["userId" : UserDefault.userID ]
      caseStatusParams.updateValue("Hello" as AnyObject, forKey: "otherNotes")
      

      结果-

      ▿  : 2 elements
          - key : "userId"
          - value : 866
      ▿  : 2 elements
          - key : "otherNotes"
          - value : "Hello"
      

      【讨论】:

        【解决方案9】:

        给定两个字典如下:

        var dic1 = ["a": 1, "c": 2]
        var dic2 = ["e": 3, "f": 4]
        

        以下是如何将 dic2 中的所有项目添加到 dic1

        dic2.forEach {
           dic1[$0.key] = $0.value
        }
        

        【讨论】:

        • 最好使用.forEach 而不是.map,因为我们不需要任何返回映射数组
        • 为了更清楚,可以是dic2.map { dic1[$0.key] = $0.value }
        【解决方案10】:
        For whoever reading this for swift 5.1+
        
          // 1. Using updateValue to update the given key or add new if doesn't exist
        
        
            var dictionary = [Int:String]()    
            dictionary.updateValue("egf", forKey: 3)
        
        
        
         // 2. Using a dictionary[key]
        
            var dictionary = [Int:String]()    
            dictionary[key] = "value"
        
        
        
         // 3. Using subscript and mutating append for the value
        
            var dictionary = [Int:[String]]()
        
            dictionary[key, default: ["val"]].append("value")
        

        【讨论】:

          【解决方案11】:

          [字符串:任意]

          对于使用[String:Any]而不是Dictionary的朋友,下面是扩展名

          extension Dictionary where Key == String, Value == Any {
              
              mutating func append(anotherDict:[String:Any]) {
                  for (key, value) in anotherDict {
                      self.updateValue(value, forKey: key)
                  }
              }
          }
          

          【讨论】:

            【解决方案12】:

            没有在字典中追加数据的功能。您只需针对现有字典中的新键分配值。它会自动为字典添加值。

            var param  = ["Name":"Aloha","user" : "Aloha 2"]
            param["questions"] = "Are you mine?"
            print(param)
            

            输出会是这样的

            [“姓名”:“阿罗哈”,“用户”:“阿罗哈 2”,“问题”:““你是我的吗?”]

            【讨论】:

              【解决方案13】:

              从 Swift 5 开始,以下代码集合有效。

               // main dict to start with
               var myDict : Dictionary = [ 1 : "abc", 2 : "cde"]
              
               // dict(s) to be added to main dict
               let myDictToMergeWith : Dictionary = [ 5 : "l m n"]
               let myDictUpdated : Dictionary = [ 5 : "lmn"]
               let myDictToBeMapped : Dictionary = [ 6 : "opq"]
              
               myDict[3]="fgh"
               myDict.updateValue("ijk", forKey: 4)
              
               myDict.merge(myDictToMergeWith){(current, _) in current}
               print(myDict)
              
               myDict.merge(myDictUpdated){(_, new) in new}
               print(myDict)
              
               myDictToBeMapped.map {
                   myDict[$0.0] = $0.1
               }
               print(myDict)
              

              【讨论】:

                【解决方案14】:
                var dict = ["name": "Samira", "surname": "Sami"]
                // Add a new enter code herekey with a value
                dict["email"] = "sample@email.com"
                print(dict)
                

                【讨论】:

                • 请提供一些信息为什么这个答案可以解决问题
                • @StephenReindl 如果你运行它,你会看到 ;)
                【解决方案15】:

                添加刚刚设置的新元素:

                listParameters["your parameter"] = value
                

                【讨论】:

                  【解决方案16】:

                  到目前为止,我发现使用 Swift 的高阶函数之一(即“reduce”)将数据附加到字典的最佳方法。按照下面的代码sn-p:

                  newDictionary = oldDictionary.reduce(*newDictionary*) { r, e in var r = r; r[e.0] = e.1; return r }
                  

                  @Dharmesh 在你的情况下,它会是,

                  newDictionary = dict.reduce([3 : "efg"]) { r, e in var r = r; r[e.0] = e.1; return r }
                  

                  如果您在使用上述语法时发现任何问题,请告诉我。

                  【讨论】:

                    【解决方案17】:

                    Swift 5 快乐编码

                    var tempDicData = NSMutableDictionary()
                    
                    for temp in answerList {
                        tempDicData.setValue("your value", forKey: "your key")
                    }
                    

                    【讨论】:

                      【解决方案18】:

                      要将新的键值对附加到字典中,您只需设置键的值。例如。

                      // Initialize the Dictionary
                      var dict = ["name": "John", "surname": "Doe"]
                       
                      // Add a new key with a value
                      
                      dict["email"] = "john.doe@email.com"
                      
                      print(dict)
                      

                      输出 -> ["surname": "Doe", "name": "John", "email": "john.doe@email.com"]

                      【讨论】:

                        【解决方案19】:

                        我添加了字典扩展

                        extension Dictionary {   
                          func cloneWith(_ dict: [Key: Value]) -> [Key: Value] {
                            var result = self
                            dict.forEach { key, value in result[key] = value }
                            return result  
                          }
                        }
                        

                        你可以像这样使用cloneWith

                         newDictionary = dict.reduce([3 : "efg"]) { r, e in r.cloneWith(e) }
                        

                        【讨论】:

                        • 您不需要克隆字典。 Dictionary 是 Swift 中的一种值类型。
                        【解决方案20】:

                        如果你想修改或更新 NSDictionary 那么 首先将其类型转换为 NSMutableDictionary

                        let newdictionary = NSDictionary as NSMutableDictionary
                        

                        然后简单地使用

                         newdictionary.setValue(value: AnyObject?, forKey: String)
                        

                        【讨论】:

                          猜你喜欢
                          • 1970-01-01
                          • 1970-01-01
                          • 1970-01-01
                          • 2021-04-24
                          • 1970-01-01
                          • 2015-06-10
                          • 1970-01-01
                          • 2015-08-30
                          • 2016-06-11
                          相关资源
                          最近更新 更多