2017-10-29 100 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 
相關問題