我希望改进我使用Swift的Array.map函数编写的闭包。
基本上,我正在使用闭包对数组进行重新映射所有元素。
基本上,我正在使用闭包对数组进行重新映射所有元素。
// Here's the array:
var numbersArray = [1, 2, 3, 4, 5]
// Here's the closure - it takes whatever number is passed into it and
// multiplies it by 2.0
var multiplier = { (currentNum: Int) -> Double in
let result = Double(currentNum) * 2.0
return result
}
// And here's how I'm calling it:
var newArray = numbersArray.map(multiplier)
这很完美地实现了功能。
但是如果我想将所有内容乘以2.1?或3.5?或任何值?换句话说,如果我希望将我要乘的数量也成为一个变量呢?并将其作为第二个参数传递到闭包中?
我尝试像这样将其添加到参数列表中:
var multiplier = { (currentNum: Int, factor: Double) -> Double in
let result = Double(currentNum) * factor
return result
}
然后将我的调用更改为:
var newArray = numbersArray.map(multiplier, 3.5)
但是我遇到了各种错误(当然,我已经尝试了各种变化)。
我做错了什么?