Count the occurences a particular integer has in an array [duplicate]
Solution 1:
Xcode 9 or later • Swift 4 or later
In Swift 4 you can use the new Dictionary method reduce(into:)
as follow:
extension Sequence where Element: Hashable {
var frequency: [Element: Int] {
return reduce(into: [:]) { $0[$1, default: 0] += 1 }
}
func frequency(of element: Element) -> Int {
return frequency[element] ?? 0
}
}
Playground testing:
let numbers = [0, 0, 1, 1, 1, 2, 3, 4, 5, 5]
print(numbers.frequency) // [2: 1, 4: 1, 5: 2, 3: 1, 1: 3, 0: 2]
print(numbers.frequency(of: 0)) // 2
print(numbers.frequency(of: 1)) // 3
print(numbers.frequency(of: 2)) // 1
print(numbers.frequency(of: 3)) // 1
print(numbers.frequency(of: 4)) // 1
print(numbers.frequency(of: 5)) // 2
By extending Collection it supports Strings as well
"aab".frequency // ["a": 2, "b": 1]
Solution 2:
Create a dictionary, store the number the first time it is found and initialize the key with 1. Increment it otherwise.
let numArray = [1, 2, 2, 2, 5]
var numCount:[Int:Int] = [:]
for item in numArray {
numCount[item] = (numCount[item] ?? 0) + 1
for (key, value) in numCount {
println("\(key) occurs \(value) time(s)")
}