iOS Dictionary with two values per key? - ios

I currently have a dictionary that contains 1 value per key. Is it possible to have 2 values per key?
var data = HomeVC.getData()
MyVariables.users = data.users;
MyVariables.img = data.img;
//MY Current dictionary with 1 value and 1 key
for (index, element) in enumerate(MyVariables.users)
{
MyVariables.dictionary[element as! String] = MyVariables.img[index]
}
I'm trying to add values from another array to this dictionary. So in total I would have 3 arrays in the same index position when calling them. 2 values and 1 key

You can use arrays or tuples as values of a dictionary:
var dictionary: Dictionary<String, (ValType1, ValType2)>
dictionary["foo"] = (bar, baz)
println(dictionary["foo"][1])

Instead of that try saving an NSArray as the value for key. The NSArray will be able to save more than 1 values and should suffice.
The lifecycle for a 2 values per key would look something like this
myDict[#"key1"] = value1;
// then set next value
myDict[#"key1"] = value2;
Now your dictionary has lost the first value and you only have access to the last one.
Your code would look something like
for (index, element) in enumerate(MyVariables.users)
{
var savedArray: [Your-Object-Type-Here]? = []
var savedArray = MyVariables.dictionary[element as! String]
if savedArray != nil {
savedArray!.append(MyVariables.img[index])
}
else {
savedArray = []
}
MyVariables.dictionary[element as! String] = savedArray
}

If your values are different types, create a custom class to hold the values. Make your dictionary keys point to objects of your custom class.

Related

fill dictionary values in loop

I have a dictionary var items = [String:String]()
Then I assign values :
for i in itemInCart {
items["param_id"] = i.modelId
//items["param_id"]?.append(i.modelId!)
}
print(items)
I have just a last value.
I know that the method append() is not applicable to dictionaries, but how can I fill it then?
This is because you are replacing param_id every time for loop i so it will always a last element you will found
You have two options, either create a unique key for each element (a bad idea) or if you want all the elements you have to create array and add it into the param_id key like:
items["param_id"] = itemInCart.map { $0.modelId }
so now your dictionary is [String:Any]() or [String:[String]]()

I have and array inside the value of dictionary

I have an dictionary and the value containts the array of string as follows
arr = ["key":"["a","b","c","d","e","f","g"]"]
I want the new array to be like
let array = ["a","b","c","d","e","f","g"]
How to parse it
You can access dictionary items in few different ways, the easiest is:
let array = arr["key"]
You may need to conditionally unwrap it
if let array = arr["key"] as? [String] {
// rest of code with array
}

Accessing Dictionary element for a tableview

I have passed a dictionary to a second view controller and assigned it to an array, I thought I could access the data easier this way:
var myAlerts: NSDictionary!
The dictionary has three elements for each: Id (which I don't care about), alertDate, and alertNote.
I'm trying to get these elements into a tableView but struggling with this.
I thought about just moving it into two arrays and accessing it that way, cumbersome but it at least gets me further down the road so to speak.
Here is the raw data from the dictionary AFTER it was past to the second controller:
{
alerts = (
{
alertDate = "2017-07-16";
alertNote = "Rob is the worlds greatest friend";
id = 2;
},
{
alertDate = "2017-07-17";
alertNote = "This is a test of the emergency system";
id = 1;
}
);
}
When I tried to move the values into two arrays with this:
func CreateArray() {
for i in 0...myAlerts.count {
alertsDate[i] = myAlerts["alerts"]["alertDate"]
alertsNote[i] = myAlerts["alerts"]["alertNote"]
}
}
I get the proverbial Type Any? has no subscript members.
Any help would be appreciated.
myAlerts with that data is now a dictionary containing an array of dictionaries. (so top level is a dictionary, with one key/value pair which is of type array of [String:Any] objects).
Since a dictionary value is of type Any, it can't infer in this case what the type of the value for the key alerts is. So you have to try cast it to a specific type first, in this case an array of dictionaries, i.e. [[String:Any]]
So this should get rid of your error:
func CreateArray() {
for i in 0...myAlerts.count {
let alertArray = myAlerts["alerts"] as! [[String:Any]]
alertsDate.append(alertArray[i]["alertDate"] as! String)
alertsNote.append(alertArray[i]["alertNote"] as! String)
}
}
Note: I had to change alertsDate and alertsNote arrays to using append as in my demo code i had no existing items in the array and using and index would have caused an error.

NSMutableDictionary replicates the last inserted index in each inserted index instead of insert the new index

I've been googling for a while, trying to find a solution to my problem and ended here. I'm trying to create a dictionary of dictionaries to load all the data in tableViewCells.
So I need a key for "name", another key for "description", another key for "image name" and like this..
I'm doing an async call so I've created a global var, nsDict which is a NSMutableDictionary and in the async parseJson Function I've created another NSMutableDictionary named jsonValues.
I use jsonValues to store the data inside the loop. The data is stored with keys too :
jsonValues["name"] = Name
And at the end of the loop I store jsonValues inside nsDict, my NSMutableDictionary global variable.
nsDict.setObject(jsonValues, forKey: c)
c += 1
At this point there is already somebody that knows for sure my issue and my mistake. But I've been trying and reading a lot of stackoverflow and didn't find the way to do something that easy.
My dictionary, is getting filled by all the jsonValues, but instead of inserting diferent values, it's copying all of them. Which is, in the first round of the loop, it insert the first value (dictionary of values). In the second loop, it insert the second dictionary of values in the first and in the second index...
At the end I got 43 same dictionaries. All of them are the copy of the last one...
Does anybody know why? I've spent two hours with this issue. Some help would be very appreciated, thanks!
private func parseJson(json : NSMutableArray, tableView : UITableView){
var jsonValues = NSMutableDictionary()
nsDict.removeAllObjects()
nsDict = NSMutableDictionary.init(capacity: 10)
var c : Int = 0
for j in json {
var nsData : NSMutableDictionary
//clean array
// jsonValues.removeAll()
//Create main value
guard let value = j.valueForKey("value")?.valueForKey("value")! else{
return
}
//Get name
guard let Name : String = (value.valueForKey("Name")?.valueForKey("en") as? String) else {
return
}
jsonValues["name"] = Name
title = "Address: "
//Get Address
if let Address = value.valueForKey("Address")?.valueForKey("en") as? String{
jsonValues["Address"] = Address
}
title = "Country: "
//Get country
if let country = geoposition.valueForKey("country") as? String{
let fCountry = title+country
jsonValues["Country"] = fCountry
}else{}
nsDict.setObject(jsonValues, forKey: c)
c += 1
}
doTableRefresh(tableView);
}
just move your var jsonValues = NSMutableDictionary() inside cycle
You create an NSMutableDictionary and insert it repeatedly. The object is inserted, not its contents. Therefore each entry contains the same object. You need to insert a new object at each index.

2 arrays into one dictionary while maintaining the indexes

I have two separate arrays that I want to import into a dictionary. Order is extremely important because both arrays must match in index
struct MyVariables {
static var users:NSArray!
static var img:NSArray!
}
var data = SearchVC.getData()
MyVariables.users = data.users; //array 1 (key)
MyVariables.img = data.img; //array 2
// Goal is to insert these arrays into a dictionary while maintaing the matching indexes on both arrays
// Dictonary (MyVariables.img, key: MyVariables.users)
A Dictionary does not have a particular order. However, if both arrays have the same length, it is quite easy to iterate over them together:
var dictionary = [NSString: AnyObject]()
for var index = 0; index < data.users.count; index++ {
let img = data.img as! NSString
dictionary[img] = data.users[index]
}
Or, as #robertvojta suggested, use the zip() method:
var dictionary = [NSString: AnyObject]()
for (user, image) in zip(data.users, data.img) {
let img = image as! NSString
dictionary[img] = user
}
The key in a dictionary in swift must be hashable. i.e., not AnyObject.
Assuming you can replace some of your untyped Swift arrays, or cast them like so:
struct MyVariables {
var users:Array<AnyObject>
var img:Array<String>
}
then you can iterate through 1 array using a preferred Swift method and access the second using indexing:
var dictionary = Dictionary<String, AnyObject>()
for (index, element) in enumerate(MyVariables.img) {
dictionary[element] = MyVariables.users[index]
}
Use for loop for travels the array in that as per index access keys and values respective array and add it in dictionary. Its so simple so you can achive your goal using it.
I hope it will help you!

Resources