在Dictionary.reduce()中迷惑约$ 0

时间:2022-08-24 21:02:17

Im trying to sum the total value of a stock, the right answer is:

我试图总结一个股票的总价值,正确的答案是:

let stock = [1.5:5, 10:2, 4.99:20, 2.30:5, 8.19:30]
let stockSum = stock.reduce(0, { 
    $0 + $1.key * Double($1.value)
})

But my conception is:

但我的观点是:

...
let stockSum = stock.reduce(0, { 
    $0.key * Double($0.value) + $1.key * Double($1.value)
})

Definitely it returns an error, anyone can help me to explain it?

肯定会返回错误,任何人都可以帮我解释一下吗?

1 个解决方案

#1


1  

Below is the parameter list for the reduce method

下面是reduce方法的参数列表

reduce(initialResult: Result, nextPartialResult: (Result, (key: Double, value: Int)) throws -> Result)

In your case, 0 is assigned to initialResult which essentially saves the sum up to a certain point while iterating. This initialResult is passed in as the first parameter in $0 and the dictionaries' key,value is passed as the second parameter in $1. Hence you see $1.key and $1.value

在您的情况下,0被赋予initialResult,它基本上在迭代时将总和保存到某个点。这个initialResult作为$ 0中的第一个参数传入,字典的键值作为$ 1中的第二个参数传递。因此,你看到$ 1.key和$ 1.value

#1


1  

Below is the parameter list for the reduce method

下面是reduce方法的参数列表

reduce(initialResult: Result, nextPartialResult: (Result, (key: Double, value: Int)) throws -> Result)

In your case, 0 is assigned to initialResult which essentially saves the sum up to a certain point while iterating. This initialResult is passed in as the first parameter in $0 and the dictionaries' key,value is passed as the second parameter in $1. Hence you see $1.key and $1.value

在您的情况下,0被赋予initialResult,它基本上在迭代时将总和保存到某个点。这个initialResult作为$ 0中的第一个参数传入,字典的键值作为$ 1中的第二个参数传递。因此,你看到$ 1.key和$ 1.value