enum Product {
case Apple
case Egg
case Orange
case Banana
}
let products: [Product] = [.Apple, .Egg, .Orange, .Apple, .Orange, .Banana, .Egg, .Egg]
products.reduce([:]) { (map, product) -> [Product: Int] in
var updatedMap = map
if let value = map[product] {
updatedMap[product] = value + 1
}
else {
updatedMap[product] = 1
}
return updatedMap
} //[Orange: 2, Apple: 2, Egg: 3, Banana: 1]
一樣用繩子:
let products: [String] = ["Apple", "Egg", "Orange", "Apple", "Orange", "Banana", "Egg", "Egg"]
products.reduce([:]) { (map, product) -> [String: Int] in
var updatedMap = map
if let value = map[product] {
updatedMap[product] = value + 1
}
else {
updatedMap[product] = 1
}
return updatedMap
} // ["Apple": 2, "Egg": 3, "Orange": 2, "Banana": 1]
或者通過擴展爲所有哈希的序列類型:
extension SequenceType where Generator.Element: Hashable {
func countElements() -> [Generator.Element : Int] {
return reduce([:]) { (map, element) -> [Generator.Element : Int] in
var updatedMap = map
if let value = map[element] {
updatedMap[element] = value + 1
}
else {
updatedMap[element] = 1
}
return updatedMap
}
}
}
products.countElements() //["Apple": 2, "Egg": 3, "Orange": 2, "Banana": 1]
來源
2016-07-15 09:00:48
JMI
爲什麼你有愚弄的陣列?爲什麼當你添加到數組中時你不合並? – Wain