您可以链接 a ,flatMap
然后reduce
对您的symbolSet
,进行操作
- 该操作将成员的
flatMap
尝试转换应用于symbolSet
String
- 以下操作计算中的符号
reduce
的加权和(对于成功转换为实例的符号)count
symbolSet
String
示例设置:
struct Item {
let value: Int
init(_ value: Int) { self.value = value }
}
let symbolDictionary = [
"+" : Item(1),
"-" : Item(2),
"/" : Item(4),
"*" : Item(8)
]
var symbolSet = NSCountedSet()
symbolSet.add("*") // accumulated: 8
symbolSet.add("/") // accumulated: 8 + 4 = 12
symbolSet.add("+") // accumulated: 12 + 1 = 13
symbolSet.add("-") // accumulated: 13 + 2 = 15
symbolSet.add("+") // accumulated: 15 + 1 = 16
flatMap
用链式和运算计算加权累加和reduce
(预期结果:16
):
let total = symbolSet
.flatMap { $0 as? String } /* <- attempted conversion of each symbol to 'String' */
.reduce(0) { $0 + symbolSet.count(for: $1) * (symbolDictionary[$1]?.value ?? 0) }
/* | ^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
| | If a key exists for the given symbol as a
| | String, extract the 'value' property of the
| | 'Item' value for this key, otherwise '0'.
| |
| Multiply '...value' or '0' with the 'count' for the given symbol.
\
Add the product to the accumulated sum of the reduce operation. */
print(total) // 16, ok