2017-10-29 10 views
0

私は複数の値(倍精度)を持つ配列を持っていますが、その多くは重複しています。私はすべてのユニークな値のリストを返したり、配列に何らかの値が何回現れたかを数えたりしています。私はSwiftにはかなり新しく、いくつかのことを試しましたが、これを達成するための最良の方法は不明です。Swift 4 - 配列から重複した値の数を返すには?

このような何か:30.25で65.0で 「3、55.5で2、2: [65.0、65.0、65.0、55.5、55.5、30.25、30.25、27.5]

は、(例えば)印刷し、27.5で1。

私はこれを達成する方法ほどの出力を心配していません。

ありがとうございます!

+0

を印刷します'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

ifは単一の文で置き換えることができます '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を拡張することができます:あなたはFoundationフレームワークを使用して気にしない場合は

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 
関連する問題