I have a dictionary which contains key and items model for the values.
var selectedDic: [String: [Item]] = [:]
- Actually I am trying to make a string with dictionary key and key has multiple value separated by comma.
- And if I add more values to key it should add values to specific key.
priceandpublisherare keys anditemIdis the value.
I need this string: price:10-25;publisher:576,925,1737
Dictionary Print:
[
"price": [
Babil.Item(name: Optional("10 - 25"),
itemId: Optional("10-25"))
],
"publisher": [
Babil.Item(name: Optional("ABCD"),
itemId: Optional("576")),
Babil.Item(name: Optional("DEFG"),
itemId: Optional("925")),
Babil.Item(name: Optional("HIJK"),
itemId: Optional("1737"),
)
]
]
My code:
var itemString: [String: String] = [:]
var str: [String] = []
for (key, value) in selectedDic {
value.forEach { a in
if str.firstIndex(of: key) == nil {
str.append(a.itemId!)
}
}
let final = str.joined(separator: ",")
itemString.updateValue(final, forKey: key)
}
let priceStr = itemString["price"]?.compactMap{ $0.name }.joined(separator: ","); let publisherStr = itemString["publisher"]?.compactMap{ $0.itemId } .joined(separator:","); let finalStr = [priceStr, publisherStr].compactMap{ $0 }.joined(separator: ";")or something like that? But it would help to know what's your current output, can there be more than one price? Why use a Dict and not another custom struct? WhynameANDitemIdare BOTH optional inItem? Is that normal?["price": "10-25", "publisher": "10-25,576,925,1737"]10-25 in publisher too.