2017-10-29 98 views
0

我有一个数组有多个值(双打),其中许多是重复的。我想返回或打印所有唯一值的列表,以及给定值出现在数组中的次数。我对Swift非常陌生,我尝试了几种不同的东西,但我不确定完成这个的最好方法。Swift 4 - 如何从数组中返回重复值的计数?

像这样: [65.0,65.0,65.0,55.5,55.5,30.25,30.25,27.5]

将打印(例如): “3在65.0,2在55.5,2 30.25 ,1在27.5。“

我并不十分关心输出和完成这个的方法。

谢谢!

+0

如果你不介意使用Foundation框架,看看'NSCountedSet'类。 – rmaddy

回答

1

您可以枚举整个数组并将值添加到字典中。

var array: [CGFloat] = [65.0, 65.0, 65.0, 55.5, 55.5, 30.25, 30.25, 27.5] 
var dictionary = [CGFloat: Int]() 

for item in array { 
    dictionary[item] = dictionary[item] ?? 0 + 1 
} 

print(dictionary) 

,或者你可以做的foreach对数组:

array.forEach { (item) in 
    dictionary[item] = dictionary[item] ?? 0 + 1 
} 

print(dictionary) 

或@rmaddy说:

var set: NSCountedSet = [65.0, 65.0, 65.0, 55.5, 55.5, 30.25, 30.25, 27.5] 
var dictionary = [Float: Int]() 
set.forEach { (item) in 
    dictionary[item as! Float] = set.count(for: item) 
} 

print(dictionary) 
+0

如果可以用单个语句替换'dictionary [item] = dictionary [item] ?? 0 + 1'更好,只是使用CountedSet :) –

+0

@DavidBerry,我已经更新了我的答案,谢谢。 – Mina

3

由于@rmaddy已经评论你可以使用基金会NSCountedSet如下:

import Foundation // or iOS UIKit or macOS Cocoa 

let values = [65.0, 65.0, 65.0, 55.5, 55.5, 30.25, 30.25, 27.5] 
let countedSet = NSCountedSet(array: values) 
print(countedSet.count(for: 65.0)) // 3 
for value in countedSet.allObjects { 
    print("Element:", value, "count:", countedSet.count(for: value)) 
} 

您还可以扩展NSCountedSet返回元组数组或字典:

extension NSCountedSet { 
    var occurences: [(object: Any, count: Int)] { 
     return allObjects.map { ($0, count(for: $0))} 
    } 
    var dictionary: [AnyHashable: Int] { 
     return allObjects.reduce(into: [AnyHashable: Int](), { 
      guard let key = $1 as? AnyHashable else { return } 
      $0[key] = count(for: key) 
     }) 
    } 
} 

let values = [65.0, 65.0, 65.0, 55.5, 55.5, 30.25, 30.25, 27.5] 
let countedSet = NSCountedSet(array: values) 
for (key, value) in countedSet.dictionary { 
    print("Element:", key, "count:", value) 
} 

这将打印

Element: 27.5 count: 1 
Element: 30.25 count: 2 
Element: 55.5 count: 2 
Element: 65 count: 3 
相关问题