我正在尝试编写一个通用的直方图函数,它可以操作一个Array
,但是我遇到了困难,因为类型'Element'不符合协议'Hashable'。
extension Array {
func histogram() -> [Array.Element: Int] {
return self.reduce([Array.Element: Int]()) { (acc, key) in
let value = (acc[key] == nil) ? 1 : (acc[key]! + 1)
return acc.dictionaryByUpdatingKey(key: key, value: value)
}
}
}
dictionaryByUpdatingKey(...)
方法会按照以下方式修改现有的字典:
extension Dictionary {
func dictionaryByUpdatingKey(key: Dictionary.Key, value: Dictionary.Value) -> Dictionary {
var mutableSelf = self
let _ = mutableSelf.updateValue(value, forKey: key)
return mutableSelf
}
}
我试过使用
AnyHashable
替换Array.Element
,并强制转换key as! AnyHashable
,但这种方法不太优雅,最好的做法是返回值类型应该与Array.Element
相同,而非AnyHashable
。
我希望能按照下面的方式使用Array
扩展:
let names = ["Alex", "Alex", "James"]
print(names.histogram()) // ["James": 1, "Alex": 2]
或者
let numbers = [2.0, 2.0, 3.0]
print(numbers.histogram()) // [3.0: 1, 2.0: 2]
reduce(into:updateAccumulatingResult:)
的知识,它在这种情况下更加高效。 - Martin R