fill dictionary values in loop - ios

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]]()

Related

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.

Swift 3: how to sort Dictionary's key and value of struct

This is my Struct,by Swift 3. I know the Dictionary is not stored sequence like an Array and that is my problem. I want to get my Dictionary sequence as I set in ViewArray. I can get the ctC Dictionary, but how can i sort the keys or values as i set in ViewArrayplease and appreciate the help.
struct CTArray {
var ctname: String
var ctkey: String
var ctC: [String:String]
}
var ViewArray:[CTArray] = []
ViewArray += [CTArray(ctname: "kerish", ctkey: "KH", ctC: ["mon":"Apple", "kis":"aone", "Bat":"Best", "orlno":"bOne"])]
ViewArray += [CTArray(ctname: "tainers", ctkey: "TNN", ctC: ["letGor":"one", "washi":"testing", "monk":"lasth"])]
ViewArray += [CTArray(ctname: "techiu", ctkey: "TCU", ctC: ["22":"tt", "wke":"303", "lenth":"highest"])]
i want to show them in my TableView Cell sorted like these:
the ViewArray[0].ctC.key sorted like [mon, kis, Bat, orlno]
the ViewArray[1].ctC.key sorted like [letGor, washi, monk]
the ViewArray[2].ctC.value sorted like [tt, 303, highest]
It is not clear to me what you are asking, but I'll offer this in case it helps.
I know the Dictionary is not stored sequence like an Array and that is my problem.
If you want to access a dictionary by a certain order of its keys then you can create an array of just the keys in the order you required and use that to access the dictionary. An example is probably easier to follow:
Starting with one of your dictionaries:
let dict = ["mon":"Apple", "kis":"aone", "Bat":"Best", "orlno":"bOne"]
print(dict)
this output:
["Bat": "Best", "kis": "aone", "orlno": "bOne", "mon": "Apple"]
which is not what you want. Now introduce a key array and use that to access the dictionary:
let keyOrder = ["mon", "kis", "Bat", "orlno"]
for key in keyOrder
{
print("\(key): \(dict[key]!)")
}
this outputs:
mon: Apple
kis: aone
Bat: Best
orlno: bOne
which is the order you wish.
The same idea can be used anywhere you want to use/show/etc. the keys in a particular order, by using the keyOrder array as part of dictionary access you are making it appear as though the dictionary entries are "stored in sequence" as you put it.
HTH
var object1 = viewArray[0].ctC.flatMap({$0.key})
var object2 = viewArray[1].ctC.flatMap({$0.key})
var object3 = viewArray[2].ctC.flatMap({$0.value})
print(object1)
print(object2)
print(object3)
Outputs:
["Bat", "kis", "orlno", "mon"]
["letGor", "monk", "washi"]
["highest", "tt", "303"]

iOS Dictionary with two values per key?

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.

Create an array in swift

I'm searching really much, but maybe I can't understand the results.
I found only that a array in SWIFT have as index int-values
var myArray = [String]()
myArray.append("bla")
myArray.append("blub")
println(myArray[0]) // -> print the result bla
But I will add a String with an String as index-key
var myArray = [String:String]()
myArray.append("Comment1":"bla")
myArray.append("Comment2":"blub")
println(myArray["Comment1"]) // -> should print the result bla
How should i declare the array and how I can append a value then to this array?
Your second example is dictionary
myArray["key"] = "value"
If you want array of dictionaries you would have to declare it like this
var myArray: [[String: String]]
Your first example is an array. Your second example is a dictionary.
For a dictionary you use key value pairing...
myArray["Comment1"] = "Blah"
You use the same to fetch values...
let value = myArray["Comment1"]
println(value)
You got the concept of array in the first example but for the second one you need a dictionary as they operate on key value pair
// the first String denotes the key while the other denotes the value
var myDictionary :[String:String] = ["username":"NSDumb"]
let value = myDictionary["username"]!;
println(value)
Quick reference for dictionaries collection type can be found here

Resources