I recently started working with swift. I am using below code to cast string to nsmutabledictionary.
print(response);
let responseData = response.data(using: .utf8)!
var json: NSMutableDictionary = try JSONSerialization.jsonObject(with: responseData, options: []) as! NSMutableDictionary;
The response from server for request is like below.
{"token1":"blah.blah.blah","token_type":"smarty","expires_in":1209600,"token2":"blah.blah.blah"}
I am stuck here. Please help.
This is no surprise because it's exactly the same behavior as in Objective-C.
In ObjC you cannot cast an immutable type to a mutable. Running this code
raises an exception
because the type remains immutable. You have to create a new
NSMutableDictionaryinstanceIronically – I'm still talking about ObjC – in case of
NSJSONSerializationthe famous option.mutableContainerscomes in. With this option you can create a mutable array / dictionary directly, please note, only in Objective-C.On the other hand in Swift this option makes no sense anyway because Swift
Dictionary/Arrayand theNSMutable...counterparts are not related to each other, and in Swift you can make a (native) type mutable simply with thevarkeyword.So write
The bottom line is:
Don't use
NSMutable...collection types in Swift at all.