I'm looking for a way to use NSCountedSet
in a more Swift
-like way (whatever that means).
Consider the following snippet that I basically translated directly from Objective C
. I iterate over each symbol (a String
) in the set, get its corresponding count, and look up a value for that symbol in a dictionary. Then I multiply that value with the count and add it to the total.
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!)
}
It works, but I am a bit concerned about the unwrapping that Xcode
suggested for me. So I am trying to do this a more Swift
like way so that it is more safe without all the unwrapping.
I started with something like this:
symbolSet.enumerated().map { item, count in
print(item)
print(count)
}
But count here is not the actual count, but an enumeration index.
How do I move forward with this?
You could chain a
flatMap
followed by areduce
operation on yoursymbolSet
,flatMap
operation applies attempted conversion of thesymbolSet
members toString
reduce
operation computes the weighted sum of thecount
of the symbols in thesymbolSet
(for the symbols that was successfully converted toString
instances)Example setup:
Compute weighted accumulated sum with the chained
flatMap
andreduce
operations (expected result:16
):