Printing Values of dictionary using loop - ios

I trying to print values of dictionary in serial order, like One Two Three but using below code is displaying random value from dictionary. How can i rectify it! Thank you !!
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
for keys in someDict.keys
{
//print (keys)
print(someDict[keys]!)
}
Output:
Two
Three
One
And when i print keys. it shows 2 3 1 :(

The keys of the dictionary is no order.
So you can use other Array to save key to ensure order.
Or..
for key in someDict.keys.sort ({
$0 < $1
}) {
print(someDict[key])
}
Chose height performance way according to your demand.

Related

How to maintain the order of the data in Dictionary in Swift?

I want to display the data in the sequence order. I am getting the json string as the response and converted into the Dictionary. I am not able to maintain the order after converted dictionary.
I know it's not guaranteed the order when we use dictionary.
How do I maintain the actual order of the data.
Note: I can't hard code the key since data's are coming from the server response.
func setupData(responseString : String)
{
// Convert string to dictionary for extracting the keys and values
// Need to maintain the order while adding the data
let content = convertToDictionary(text: responseString)
var text : String = ""
if let contentDataDict = content
{
for (key, value) in contentDataDict
{
// want to append the key and values in the sequence order
content += \(key) \n \(value)
}
}
textView.attributedText = text.htmlToAttributedString
}
.
Short answer:
You can not maintain order in the Dictionary.
Long answer:
Apple says:
Dictionaries are unordered collections of key-value associations.
Please refer this
To maintain the order you need to use the Array or create sorted Array(Ascending, Descending or by using specific key) from the Dictionary and use it.
Thank you.

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

How avoid having double loop?

From healthkit, I will receive some datas, for example steps data.
I save in my server this datas. Il have then an array of datas:
1.- startDate, endDate, value
2.- startDate, endDate, value
etc
It can be very lot of values in my server.
Then I get the values in the Healthkit. I have lot of values. Values who are in the server and new values.
I want to upload to the server only the new values.
I do so:
for each value in my server {
for each value in healthkit{
if(startDate, endDate and value are not equal to the value in the server){
then save the value in the server
}
}
}
The algo will work, but it's very very slow. I can have lot of values in the two systems. Most of them the same in the two places.
Have you an idea how to do better?
I cannot save a flag in the healthKit.
I'm using ionic with angular 4 and typescript.
This answer assumes that the data on your server and the data from healthKit are sorted in the same way, or that you can sort them without affecting anything else.
For example you can sort your data on the server and the data from healthKit by StartDate, break ties by EndDate, then break ties by value.
Now you have two sorted arrays that you want to merge. The idea is to use the merge function of merge sort explained here.
You will end up with an array containing all the data without repetitions, which you can save on your server.
Edit:
void mergeArrays(int arr1[], int arr2[], int n1,
int n2, int arr3[])
{
int i = 0, j = 0, k = 0;
// Traverse both array
while (i<n1 && j <n2)
{
// Check if current element of first
// array is smaller than current element
// of second array. If yes, store first
// array element and increment first array
// index. Otherwise do same with second array
if (arr1[i] < arr2[j])
arr3[k++] = arr1[i++];
else if (arr2[j] < arr1[i])
j++;
else
j++,i++;
}
// Store remaining elements of first array (healthKit Array)
while (i < n1)
arr3[k++] = arr1[i++];
}
I think I need a bit more context to understand the problem. By "new" values, are you including entries that have been modified, or just new entries that have been added?
If you only need the new values, and they are being added to the end of the array on the client side, then you can just take them from the end of the array.
const new_count = healthkit.length - myserver.length, // number of new entries
index_start = healthkit.length - new_count, // index in healthkit array where new entries start
new_values = healthkit.slice(index_start); // new array containing only new entries
addNewValues(new_values);
Now you have the new values in a separate array, and you can update them to the server.
If it is the case that you do need to update values that have changed, you can iterate over both arrays (only once, and at the same time) and find the differences. I am going to assume that the entries are in the same index for both arrays. I'm also assuming the "value" key is the only one you want to compare. You can do the following to find the values that have been modified.
const modified_values = [];
myserver.forEach(function(entry, i) { // iterate over server array
let healthkit_entry = healthkit[i]; // get healthkit entry with same index
if(entry.value !== healthkit_entry.value) { // see if value has changed
modified_values.push(healthkit_entry); // if changed, add to modified array
}
});
updateModifiedValues(modified_values);
Now the modified_values array has all of the modified entries from the healthkit array.

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

Group TableView items from NSArray returned in JSON Response in Swift

I have a table view and I want to populate the table view with the values provided to me in a JSON response in the form of NSArray and I have used the code below to extract this NSArray:
dispatch_async(dispatch_get_main_queue(), {
print(json)
if let listDictionary = parseJSON["list"] as? NSArray {
print("LIST: \(listDictionary)")
}
})
In JSON response, I get the following array of two elements as shown below:
list = (
{
"is_cover" = 0;
"is_recommand" = 0;
name = "Helena's Signature Dish";
ord = 5;
price = "105.00";
remark = "Helena's special made dish is one of the most priced and delicious dishes in the whole world.";
thumb = "56c351887a0e0.jpg";
},
{
"is_cover" = 0;
"is_recommand" = 0;
name = "Pineapple Fried Rice";
ord = 6;
price = "110.00";
remark = "We have the most delicious pineapple rice in the whole world!";
thumb = "56c704e15da79.jpg";
}
);
Now I want to show the value "name", "price" and "remark" fields from each element in the array into a UITableView.
But I can't find a way to break the values for name, price and remark for each element and put them into an another array so they can be displayed in a table view somehow because each element contains a very long string and I only need to extract some values from this string. Can anyone please help me with this as I'm very new to Swift.
Thanks!
You don't need to make a second array, Only extarct particular json from array in cellForRowatIndexPath on dictinary by objectatindex method of array and now you can access.
You can achieve it by creating a model Class which contains only
those properties which you needed.
Once you get the response array from server , iterate though each
dictionary and create a Model Object.Add this model objects in the
Array.
Use this model object in the Array for applying data in your cell using the index
One more thing to add is always prefer using objects as it gives (.)dot syntax & autosuggestion, so there will be less chances of
making mistakes. As if you use Dictionary there will be more chances
of using incorrect key getting crash
I fixed this by putting values in "name", "price" and "remark" fields into another array using flatMap as shown below:
let nameArray = listArray.flatMap({ element in (element["name"] as? String)! })
And then I got something like:
Name's: (
"Helena's Special Dish",
"Pineapple Fried Rice"
)
and then in the tableView function for cellForRowAtIndexPath I grouped the values in tableview.

Resources