1

我正在寻找一种以NSCountedSetSwift相似的方式使用的方法(无论这意味着什么)。

考虑以下我基本上直接从Objective C. 我遍历String集合中的每个符号 (a),获取其对应的计数,并在字典中查找该符号的值。然后我将该值乘以计数并将其添加到总数中。

var total = 0

for symbol in symbolSet {
    let count = symbolSet.count(for: symbol)
    let item = symbolDictionary[symbol as! String]
    let value = item?.value

    total+= (count * value!)
}

它有效,但我有点担心Xcode为我建议的展开。所以我试图以一种更Swift相似的方式来做这件事,这样在没有所有展开的情况下它会更安全。

我从这样的事情开始:

symbolSet.enumerated().map { item, count in
    print(item)
    print(count)
}

但是这里的count并不是实际的count,而是一个枚举索引。

我该如何继续前进?

4

1 回答 1

1

您可以链接 a ,flatMap然后reduce对您的symbolSet,进行操作

  • 该操作将成员的flatMap尝试转换应用于symbolSetString
  • 以下操作计算中的符号reduce的加权和(对于成功转换为实例的符号)countsymbolSetString

示例设置:

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
于 2016-12-01T17:30:26.497 回答