在 Swift 中使用 reduce 构建字典
Build a Dictionary with reduce in Swift
我正在尝试使用 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 { [=13=] }.filter {[=13=].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]]]'
这对我来说有点晦涩难懂。
您可以迭代键并使用 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 { [=10=].contains(key) }
}
return dictionary
}
print(dictionary(keys: squares, containing: unitlist))
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 { [=10=].contains(key) }
}
我正在尝试使用 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 { [=13=] }.filter {[=13=].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]]]'
这对我来说有点晦涩难懂。
您可以迭代键并使用 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 { [=10=].contains(key) }
}
return dictionary
}
print(dictionary(keys: squares, containing: unitlist))
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 { [=10=].contains(key) }
}