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 }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.