How to append elements into a dictionary in Swift?

后端 未结 19 1976
旧时难觅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-28 23:58

    Up till now the best way I have found to append data to a dictionary by using one of the higher order functions of Swift i.e. "reduce". Follow below code snippet:

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

    @Dharmesh In your case, it will be,

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

    Please let me know if you find any issues in using above syntax.

提交回复
热议问题