Gio*_*ano 4 reduce dictionary functional-programming swift
我正在尝试使用 Swiftreduce从 Swift 中的集合构建字典。我有以下变量:
var _squares  : [String] = []
var _unitlist : [[String]] = []
var _units    = [String: [[String]]]()
我想_units通过以下方式填充字典:
_squares_unitlist并仅过滤包含该元素的列表给你举个例子。如果我们有:
squares = ["A"]
unitlist = [["A", "B", "C"], ["A", "C"], ["B", "C", "F"]]
预期的输出应该是字典 di "A" 作为键和[["A", "B", "C"], ["A", "C"]]值。
我试过这样的事情:
_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
    }
}
我使用了flatMap两次迭代,然后我进行了过滤并尝试使用reduce.
但是,使用此代码,我面临以下错误:Cannot assign value of type '[(key: String, value: [[String]])]' to type '[String : [[String]]]'这对我来说有点晦涩。
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) }
}