NSDictionary init with multiple objects and keys - ios

I've been recently trying to figure out how to init a Dictionary in swift like i used to do in Objective-c:
NSMutableDictionary *loginDictionary = [[NSMutableDictionary alloc] initWithObjects:#[UsernameTextfield.text,PasswordTextfield.text] forKeys:#[#"username",#"password"];
i tried to write it in Swift :
let userDictionary = NSMutableDictionary.init(object: [usernameTextField.text,passwordTextField.text], forKey: ["username","password"])
But i get an error:
Contextual type AnyObject cannot be used with array literal.

First of all, you have to use the same method, with objects and forKeys (note the plural).
Then you need to tell the compiler what type is each object, in your case it's strings from Optional text labels, so you could do something like this:
if let name = usernameTextField.text as? String, let pass = passwordTextField.text as? String {
let userDictionary = NSMutableDictionary(objects: [name, pass], forKeys: ["username", "password"])
}

You are Passing Objects and Keys in NSMutableDictionary as below, replace your code as below.
let userDictionary = NSMutableDictionary(objects: [usernameTextField.text,passwordTextField.text], forKeys: ["username","password"])

Related

Create NSMutableDictionsry in Swifty-Json

I want to create a NSMutableDictionary using Swifty-Json.
I have declared dictionary like this
var arrTest = Array<JSON>()
var testDict : JSON = [:]
testDict.dictionaryObject?.updateValue(arrTest[0]["test"][indexPath.item]["xyz"], forKey: "abc")
Now I am unable to setValueForKey in this Dictionary.
Can Someone tell me how to create a NSMutableDictionary using SwiftyJson and also how to insert, update and delete values in this dictionary.
Thanks in advance
Don't use NSMutableDictionary in Swift, use Swift built-in type Dictionary instead. Declaring it as var will make it mutable.
You also don't use updateValue for Dictionary, simply use a subscript:
var testDict : [String : AnyObject] = [:]
let key = "abc"
let value = arrTest[0]["test"][indexPath.item]["xyz"]
testDict[key] = value
// add object
let testobj = ["qwe" : arrTest[0]["test"][indexPath.item]["xyz"]]
dictSelectedOption = JSON(testobj)
//remove objects
dictSelectedOption.dictionaryObject?.removeAll()

Copy of NSDictionary to NSMutableDictionary

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
let f : NSDictionary = NSDictionary()
var g = f.mutableCopy()
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"]

Convert from Objective-C NSArray to swift [[String:String]]?

I want to convert from NSArray to swift array [Dictionary<String:String>]
Any help ?
Simple as that:
let someArray = myArray as? [[String:String]]
Optional casting is recommended if you want to make sure you don't get any crashes when converting. You can then use it in if-let constructions like this:
if let dictArray = myArray as? [[String:String]] {
// do something with the array of dictionaries
}
BTW, your initial definition was not correct, there's no such thing as Dictionary<String:String>, the correct definition is Dictionary<String, String>.

how to get Number value form dictionary

I am accessing data from JSON and storing it in dictionary 1 and passing this dictionary 1 to another view controller's dictionary 2. The view controller has all the details mainly 12 labels. I have managed to access the strings but i am not able to get the number values. Please have a look at the code.
DetailsViewController
var dict2 = [String : AnyObject]()
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.lblTopName.text = self.dict2["toponymName"] as? String
self.lblFcodeName.text = self.dict2["fcodeName"] as? String
self.lblName.text = self.dict2["name"] as? String
self.lblCountryCode.text = self.dict2["countrycode"] as? String
self.lblFCL.text = self.dict2["fcl"] as? String
self.lblFclName.text = self.dict2["fclName"] as? String
self.lblWikipedia.text = self.dict2["wikipedia"] as? String
self.lblFcode.text = self.dict2["fcode"] as? String
self.lblLongitude.text = self.dict2["lng"] as? String
Note. The last line of code that is longitude a number value. If I replace String with NSNumber it gives me the following error:
Cannot assign value of type NSNumber to type String
Forced cast should be avoided as much as possible, as it can lead to unexpected crashes. (self.dict2["lng"] as! NSNumber) will crash your application if for some reason the dictionary ends up without the lng key.
Your last line should be:
self.lblLongitude.text = self.dict2["lng"]?.description
This is guaranteed not to crash, as description exists on any object, and in case the dictionary somehow doesn't contain the "lng" key, you'll get a simple nil to assign to text.
plese try this if self.dict2["lng"] never null
self.lblLongitude.text = (self.dict2["lng"] as! NSNumber).stringValue
else if can be null then
self.lblLongitude.text = self.dict2["lng"]?.description
you can get integer value from dictionary like
int value = dict["integerValue"].integerValue // or doubleValue etc
and if you need string it can be like
self.lblLongitude.text = "\(self.dict2["lng"]. doubleValue)"
You can write like this
self.lblLongitude.text = String(format: "%f",self.dict2["lng"]!)

How to convert a Swift dictionary with enum keys to an NSDictionary?

I can't convert a Swift dictionary to an NSDictionary. I'm using a Swift enumerate as the key of my dictionary:
enum StringEnum : String {
case Lemon = "lemon"
case Orange = "orange"
}
var swiftDictionary = [StringEnum: AnyObject]()
swiftDictionary[.Lemon] = "string value"
swiftDictionary[.Orange] = 123
When I try to convert it to a NSDictionary with the as keyword:
let objcDictionary: NSDictionary = swiftDictionary as NSDictionary
I get the compiler error:
'[StringEnum : AnyObject]' is not convertible to 'NSDictionary'
Can these types of dictionaries be converted or do I need to loop the Swift dictionary and create an NSDictionary manually?
I think if your dictionary have enum values then you can not convert it to NSDictionary but another way to do that is:
//change the type of your dict to [String: AnyObject]()
var swiftDictionary = [String: AnyObject]()
//you can store rawValue as a key
swiftDictionary[StringEnum.Lemon.rawValue] = "string value"
swiftDictionary[StringEnum.Orange.rawValue] = 123
let objcDictionary = swiftDictionary as NSDictionary //["lemon": "string value", "orange": 123]
Hope this will help.
None of them (StringEnum, String, Dictionary) are obj-c types, therefore you cannot do that implicitly. You definitely need a loop for that.
It is complaint because you cannot save values type to NSDictionary (enums is a value type). You have to wrap it to a NSNumber or any other type.

Resources