I m mapping data that come from service with using dictionary [String: String]. I collect them dictionary array. For example, if their parent ids are the same, I want to add their values by array value.
["ParentId": "1","Value": "["Giyim","Aksesuar","Ayakkabı"]"]
It is also the reason I don’t know parent id sometimes on the left sometimes on the right in photo
Here is my code and its output.
struct Categories {
let parentId: String
let values: [String]
}
for result in results {
if result?.parentCategoryId != "" {
for docId in self.docIds {
if result?.parentCategoryId == docId {
//print(result?.name)
var values = [String]()
values.append(result?.name ?? "")
self.newCat.append(Categories(parentId: docId, values: values))
}
}
}
}
2
Answers
Using the
struct
approach, you could do something like this (you’ll need to adapt it to your code, but that should be straightforward):Which yields this:
I still wonder whether you maybe just want a
Dictionary
that is keyed by theparentId
, but not knowing your use case, it’s hard to say.Problem
As far as I understand from the description you want to map some service data structure to a dictionary where key is parentId and value is an array of some items referred to parentId.
I believe your problem comes from a misunderstanding of the concept of dictionary as a data structure.
[String: String]
is dictionary where keys and their associated values are of String type. For example:That means you cannot store associated values of String and Array types in the same dictionary, as you already told the compiler you would like to store only strings.
This is because key-value pairs are stored in the dictionary without order. This is how dictionaries work 🙂 I’d strongly recommend reading some short official materials to get used to them.
Possible solutions
In your case i would suggest either use some struct:
OR [personally this appeals to me more]
Store data in
[String: [String]]
dictionary, where the key is parentID and the associated value is an array of values.The algorithm of filling this dictionary is pretty the same: