5

I need to know that how can i make a copy of NSDictionary to NSMutableDictionary and change values of there.

Edit

I ned to know how to modify data of a NSDictionary. I got to know that

Copy data of NSDictionary to a NSMutableDictionary. and then modify data in NSMutableDictionary

3
  • In Swift use the native Dictionary type with var.
    – vadian
    Commented Jan 17, 2016 at 18:22
  • This could have been easily looked up. @vadian, that doesn't make a copy and he may need NSDictionary/NSMutableDictionary for other things. Commented Jan 17, 2016 at 18:26
  • Dictionary is value type by default so it does make a copy.
    – vadian
    Commented Jan 17, 2016 at 18:29

2 Answers 2

17
let f : NSDictionary = NSDictionary() 
var g = f.mutableCopy()
1
  • 2
    Just note that this does not make copies of objects inside the dictionary, just references Commented Jan 17, 2016 at 18:26
10

You should initialize the NSMutableDictionary using it's dictionary initializer, here's a quick example in Playground

let myDict:NSDictionary = ["a":1,"b":2]

let myMutableDict: NSMutableDictionary = NSMutableDictionary(dictionary: myDict)

myMutableDict["c"] = 3

myMutableDict["a"] // 1
myMutableDict["b"] // 2
myMutableDict["c"] // 3

Alternatively, you can declare a Swift dictionary as a var and mutate it whenever you want.

var swiftDictioanry : [String:AnyObject] = ["key":"value","key2":2]

The AnyObject value type mimics the behavior of an NSDictionary, if all types are known it can be declared like so:

var myNewSwiftDict : [String:String] = ["key":"value","nextKey":"nextValue"]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.