在 Swift 中使用 reduce 构建字典

Gio*_*ano 4 reduce dictionary functional-programming swift

我正在尝试使用 Swiftreduce从 Swift 中的集合构建字典。我有以下变量:

var _squares  : [String] = []
var _unitlist : [[String]] = []
var _units    = [String: [[String]]]()
Run Code Online (Sandbox Code Playgroud)

我想_units通过以下方式填充字典:

  • 我想迭代中的每个元素 _squares
  • 我想查看所有列表_unitlist并仅过滤包含该元素的列表
  • 构建一个字典,将每个元素作为键,并将包含此类元素的列表列表作为值。

给你举个例子。如果我们有:

squares = ["A"]
unitlist = [["A", "B", "C"], ["A", "C"], ["B", "C", "F"]]
Run Code Online (Sandbox Code Playgroud)

预期的输出应该是字典 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
    }
}
Run Code Online (Sandbox Code Playgroud)

我使用了flatMap两次迭代,然后我进行了过滤并尝试使用reduce.

但是,使用此代码,我面临以下错误:Cannot assign value of type '[(key: String, value: [[String]])]' to type '[String : [[String]]]'这对我来说有点晦涩。

Adr*_*ski 7

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) }
}
Run Code Online (Sandbox Code Playgroud)

  • Swift 是一种类型推断语言 `reduce(into: [:])` (2认同)