Bhavin_m
Bhavin_m

Reputation: 2784

How to create NSMutableDictionary in swift 2.0

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.

Upvotes: 12

Views: 25191

Answers (3)

Ducky
Ducky

Reputation: 2754

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?] 

Upvotes: 22

Bhavin_m
Bhavin_m

Reputation: 2784

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"
    ];

Upvotes: 1

Peter Foti
Peter Foti

Reputation: 5654

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]

Upvotes: 0

Related Questions