你能帮我简化下面的流程吗?
范围是计算给定数组中每个元素重复的时间.
范围是计算给定数组中每个元素重复的时间.
var test = [1,2,3,4,5,6,7,8,9,9] var testCount = [Int:Int]() for curr in test { if let x = testCount[curr] { testCount[curr] = x + 1 continue; } testCount[curr] = 1 } print(testCount)
我正在努力,以便有类似的东西:
test.map_duplicate() or map_duplicate(test)
解决方法
您可以将SequenceType扩展为具有函数freq,它完全符合您的需要.
extension SequenceType where Self.Generator.Element: Hashable { func freq() -> [Self.Generator.Element: Int] { return reduce([:]) { (var accu: [Self.Generator.Element: Int],element) in accu[element] = accu[element]?.successor() ?? 1 return accu } } }