Can I expand the dictionary to an array of pairs in Swift 5 using map/reduce
or will I have to do a for each
?
let dict = ["A": ["1","2","3","4"],
"B": ["5","6","7","8"]]
???
//result = [["A", "1"],["A", "2"],....["B", "5"],....]
Can I expand the dictionary to an array of pairs in Swift 5 using map/reduce
or will I have to do a for each
?
let dict = ["A": ["1","2","3","4"],
"B": ["5","6","7","8"]]
???
//result = [["A", "1"],["A", "2"],....["B", "5"],....]
let result = dict.map { (letter: String, digits: [String]) in
return digits.map { digit in
return [letter, digit]
}
}.reduce([]) {
$0 + $1
}
This one is shortest solution.
let result = dict.map { dic in
dic.value.map { [dic.key : $0] }
}.reduce([], +)
Here's a solution that doesn't need reduce
:
let dict = ["A": ["1","2","3","4"],
"B": ["5","6","7","8"]]
let result = dict.map { kv in kv.value.map { [kv.key, $0] } }.flatMap { $0 }