どうも、ちょげ(@chogetarou)です。
reduce()を使って辞書(Dictionary)の値(value)の合計値を取得する方法を紹介します。
方法

reduce()を使って辞書(Dictionary)の値(value)の合計値を取得するには、2つの引数を使います。
まず、辞書からreduce()を呼び出します。
そして、reduce()の第1引数に初期値、第2引数に「$0 + $1.value
」を返すクロージャーを指定します。
//dict=対象の辞書
let result = dict.reduce(0) { $0 + $1.value }
上記のreduce()は、辞書の値(value)の合計値を取得します。
使用例
import Foundation
let nums = [
"one": 1,
"two": 2,
"three": 3,
"four": 4,
"five": 5
]
let result = nums.reduce(0) { $0 + $1.value }
print(result)
出力:
15
コメント