如何检查阵列中重复的内容?

时间:2016-03-03 05:07:42

标签: ios arrays swift

我需要知道数组中重复的内容,我不知道使用什么方法来实现。 [1,2,6,8,8,8,2]。我需要它来打印8 occurs 3 times 2 occurs 2 times。我该怎么做呢。

for(var i = 0; i < numberarray.count; i++){
}

1 个答案:

答案 0 :(得分:1)

let numbers = [1,2,6,8,8,8,2]
let cs = NSCountedSet(array: numbers)

cs.forEach { if cs.countForObject($0) > 1 { print("number: \($0) has an occurance of \(cs.countForObject($0))") } }

这样的东西?

输出:

number: 2 has an occurance of 2
number: 8 has an occurance of 3