Velvet Star Monitor

Standout celebrity highlights with iconic style.

updates

How to create NSMutableDictionary in swift 2.0

Writer Matthew Barrera

Recently i update Xcode to 7 and it contains swift 2.0 compiler. Before this i made my project with older version of swift. In that version i had create NSMutableDictionary like bellow

 let dictParams:NSMutableDictionary? = ["test" : "test", "username" : txtEmail.text, "password" : txtPassword.text, "version" : "1.0", "appId" : "1", "deviceId" : "fasdfasdfrqwe2345sdgdfe56gsdfgsdfg" ];

in above code txtEmail.text and txtPassword.text is my text field and fill tha value at run time.

This code is properly working in older version of swift but after update to swift 2.0 it gives me an error like bellow

Cannot convert value of type '[String : String?]' to specified type 'NSMutableDictionary?'

what's wrong with it please guide me.

4

3 Answers

Simply by opening NSMutableDictionary or NSDictionary class interfaces from Xcode 7, you could easily see that the underlying type is actually [NSObject: AnyObject]. It means that the value can't be nil.

Unwrapping text values like txtEmail.text! or txtPassword.text! might look ok and help you to get rid of the compiling error, but it's a bad choice because technically text property of UITextField is optional and your app can crash in that case!

Do this for your safety:

let dictParams: NSMutableDictionary? = ["test" : "test", "username" : txtEmail.text ?? "", // Always use optional values carefully! "password" : txtPassword.text ?? "", "version" : "1.0", "appId" : "1", "deviceId" : "fasdfasdfrqwe2345sdgdfe56gsdfgsdfg"
]

By the way, in case it's not critical to use NSMutableDictionary, please consider using Swift dictionary like this:

var mutableDictionary = [String: AnyObject]
// OR this if the value can be nil
var mutableDictionary = [String: AnyObject?] 
1

simple change in"username" : txtEmail.text! instead "username" : txtEmail.text

so final code is like bellow

let dictParams:NSMutableDictionary? = ["test" : "test", "username" : txtEmail.text!, //Add ! here "password" : txtPassword.text!, //Add ! here "version" : "1.0", "appId" : "1", "deviceId" : "fasdfasdfrqwe2345sdgdfe56gsdfgsdfg" ];
2

txtEmail.text and/or txtPassword.text are returning an optional which is why its telling you to change the type. You could rewrite the dict as a swift dictionary (which is what I would recommend). When you do so, you can either make the object optional, or leave it as just String and bang out the optional string when you're creating the dict.

var optionalString: String?
var someDict: [String: String?] = ["test": "test", "test1": optionalString]
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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