更新时间:2022-12-10 09:50:33
Xcode 9 或更高版本 • Swift 4 或更高版本
在 Swift 4 中你可以使用新的 Dictionary 方法 reduce(into:)
如下:
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]