I'm attempting to use the new Swift 4 methods below to combine an array of dictionaries.
Dictionary(keysAndValues:uniquingKeysWith:)
You use this initializer to create a dictionary when you have a sequence of key-value tuples
SE-0165: Dictionary & Set Enhancements
https://github.com/apple/swift-evolution/blob/master/proposals/0165-dict.md
This works great with a sequence of key-value tuples:
let arrayOfTuple = [("one", 1),
("two", 2),
("three", 3)]
// [("one", 1), ("two", 2), ("three", 3)]
// ok!
let tupleDict = Dictionary(arrayOfTuple) { (_, new) in new}
// ["one": 1, "three": 3, "two": 2]
However, it gives an error for the related concept of a sequence of dictionaries:
let arrayOfDict = [
["one" : 1],
["two" : 2],
["three": 3],
]
// [["one": 1], ["two": 2], ["three": 3]]
// ERROR: generic parameter 'Key' could not be inferred
let dict = Dictionary(arrayOfDict) { (_, new) in new}
// Understandable error, as `arrayOfDict` is not "a sequence of key-value tuples"
// Would be nice if this worked, though...
It also fails with an error if you first flatmap the sequence of dictionaries into a sequence of key-value tuples:
let flatMapped = arrayOfDict.flatMap({ $0 })
// [(key: "one", value: 1), (key: "two", value: 2), (key: "three", value: 3)]
// ERROR: generic parameter 'Key' could not be inferred
let dict = Dictionary(flatMapped) { (_, new) in new}
// `flatMapped` is definitely "a sequence of key-value tuples" - why does this not compile?
This DOES work if you explicitly set the Type of the flatMap result to remove the tuple labels:
let flatMapped: [(String, Int)] = arrayOfDict.flatMap({ $0 })
Why does a tuple like [("one", 1)]
work, while [(key: "one", value: 1)]
does not?