How to append elements into a dictionary in Swift?

后端 未结 19 1972
旧时难觅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:00

    I added Dictionary extension

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

    you can use cloneWith like this

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

提交回复
热议问题