Reputation: 2243
Trying to make array of dictionaries with object, which adds keys and values during array flatMap
var parameters: [String: Any] {
var postParameters: [String: Any] = [:]
postParameters["topics"] = categories.flatMap({ toPostParameters($0) })
print(postParameters)
return postParameters
}
private func toPostParameters(_ topics: Topics) -> [String: Any] {
var params: [String: Any] = [:]
params["id"] = topics.id
params["isFound"] = topics.isFound
return params
}
when I print the postParameters value, all I get is like the following. How to remove the key and value strings appending over it.
["topicCategories": [(key: "isFound", value: true), (key: "id", value: "62ef2b63e49a"),
(key: "id", value: "632serer269"), (key: "isFound", value: true)]]
Expected
["topicCategories": [["isFound": true, "id": "62ef2b63e49a"],
["id": "632serer269","isFound": true]]]
Upvotes: 0
Views: 128
Reputation: 2551
You should use map, because flatMap
makes everything "flat" and you get a flat array of tuples instead of array of dictionaries.
class Topics {
var id = 1
var isFound = true
}
var categories = [Topics(), Topics(), Topics()]
var parameters: [String: Any] {
var postParameters: [String: Any] = [:]
postParameters["topics"] = categories.map({ toPostParameters($0) })
return postParameters
}
private func toPostParameters(_ topics: Topics) -> [String: Any] {
var params: [String: Any] = [:]
params["id"] = topics.id
params["isFound"] = topics.isFound
return params
}
print(parameters)
["topics": [["id": 1, "isFound": true], ["id": 1, "isFound": true], ["isFound": true, "id": 1]]]
Good article to understand the difference between map
, compactMap
and flatMap
.
Upvotes: 1