I am trying to use the Swift reduce
to build a dictionary from collections in Swift .
I have the following variables:
var _squares : [String] = []
var _unitlist : [[String]] = []
var _units = [String: [[String]]]()
I want to fill the _units
dictionary int the following way:
_squares
_unitlist
and filter only the ones that contain the elementTo give you an example. If we have:
squares = ["A"]
unitlist = [["A", "B", "C"], ["A", "C"], ["B", "C", "F"]]
the expected output should be a dictionary di "A" as key and [["A", "B", "C"], ["A", "C"]]
as value.
I tried with something like this:
_units = _squares.flatMap { s in
_unitlist.flatMap { $0 }.filter {$0.contains(s)}
.reduce([String: [[String]]]()){ (dict, list) in
dict.updateValue(l, forKey: s)
return dict
}
}
I used flatMap
twice to iterate, then I filtered and I tried to use reduce
.
However, with this code I am facing the following error: Cannot assign value of type '[(key: String, value: [[String]])]' to type '[String : [[String]]]'
that is a bit obscure to me.
let squares = ["A"]
let unitlist = [["A", "B", "C"], ["A", "C"], ["B", "C", "F"]]
let units = squares.reduce(into: [String: [[String]]]()) { result, key in
result[key] = unitlist.filter { $0.contains(key) }
}
You can iterate over the keys and construct the values by using filter
. Here is a playground:
import PlaygroundSupport
import UIKit
let squares = ["A"]
let unitlist = [["A", "B", "C"], ["A", "C"], ["B", "C", "F"]]
func dictionary(keys: [String], containing values: [[String]]) -> [String: [[String]]]{
var dictionary: [String: [[String]]] = [:]
keys.forEach { key in
dictionary[key] = values.filter { $0.contains(key) }
}
return dictionary
}
print(dictionary(keys: squares, containing: unitlist))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With