我正在尝试使用Swift reduce
从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]]]'
对我来说有点模糊。
答案 0 :(得分:4)
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) }
}
答案 1 :(得分:1)
您可以使用filter
迭代键并构造值。这是一个游乐场:
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))