I am having an array of dictionaries with columnId
and columnValue
as a pair. Now i need to flatten it as columnId
as the key and columnValue
as the value of it. How is it possible to do with swift higher order functions?
let arrayOfDictionaries = [["columnId": 123, "columnValue": "sample text"], ["columnId": 124, "columnValue": 9977332]]
//The end result should be:
flattenedDictionary: [String: Any] = ["123": "sample text", "124": 9977332]
Note: Result dictionary will be in the form of [String: Any]
2
Answers
You can do this in two steps;
compactMap
Dictionary(uniqueKeysWithValues:)
Note that this code will throw an exception if there are duplicate keys. You should either take steps to ensure the
columnId
values are unique or useDictionary(keysAndValues:, uniquingKeysWith:)
to resolve id clashes.This would work: