辞書の値を更新するカスタム オペレーターを作成するエレガントな方法はありますか?
より具体的には、特定のキーに対応する整数値をインクリメントするプレフィックス演算子が必要です。
prefix operator +> {}
prefix func +> //Signature
{
...
}
var d = ["first" : 10 , "second" : 33]
+>d["second"] // should update d to ["first" : 10 , "second" : 34]
これは、機能的な方法を使用して実現可能です。たとえば、配列内の要素の頻度を計算するには、次のようにします。
func update<K,V>(var dictionary: [K:V], key: K, value: V) -> [K:V] {
dictionary[key] = value
return dictionary
}
func increment<T>(dictionary: [T:Int], key: T) -> [T:Int] {
return update(dictionary, key: key, value: dictionary[key].map{$0 + 1} ?? 1)
}
func histogram<T>( s: [T]) -> [T:Int] {
return s.reduce([T:Int](), combine: increment)
}
let foo = histogram([1,4,3,1,4,1,1,2,3]) // [2: 1, 3: 2, 1: 4, 4: 2]
しかし、カスタム演算子を使用して同じことをしようとしています