2016-08-16 118 views
0

我有几个阵列,我正在追加到一个新的更大的阵列,并期待一些重复,我需要按频率列出的新阵列中的所有对象。列出按频率排列的对象,频率最高的频率

例如:

a = ["Swift","iOS", "Parse"] 
b = ["Swift", "iOS", "Parse"] 
c = ["iOS", "Parse"] 
d = ["Parse"] 

let bigArray:[String] = a+b+c+d 

如何创建从bigArray一个新的数组,它是通过频率从最分类到至少不重复的,因此它打印:

["Parse", "iOS", "Swift"] 

回答

2
let a = ["Swift","iOS", "Parse"] 
let b = ["Swift", "iOS", "Parse"] 
let c = ["iOS", "Parse"] 
let d = ["Parse"] 

var dictionary = [String: Int]() 

for value in a+b+c+d { 
    let index = dictionary[value] ?? 0 
    dictionary[value] = index + 1 
} 

let result = dictionary.sort{$0.1 > $1.1}.map{$0.0} 
print(result) 
//["Parse", "iOS", "Swift"]