How to append elements into a dictionary in Swift?

后端 未结 19 1968
旧时难觅i
旧时难觅i 2020-11-28 23:31

I have a simple Dictionary which is defined like:

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

Now I want to add an element into t

19条回答
  •  鱼传尺愫
    2020-11-29 00: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")
    

提交回复
热议问题