考虑到这些值
let lists: [[Double]] = [[1.1, 2.2, 3.3], [4.4, 5.5, 6.6]]
let sum = lists.reduce(0) { $0 + $1.reduce(1, combine: *) }
如果您定义了这个扩展名
extension SequenceType where Generator.Element == Double {
var product : Double { return reduce(1.0, combine: *) }
}
那么,您可以编写
let sum = lists.reduce(0) { $0 + $1.product }
使用上述定义的扩展程序,您还可以编写以下内容:
let sum = lists.map { $0.product }.reduce(0, combine:+)
如果我们定义这两个后缀运算符
postfix operator +>{}
postfix func +>(values:[Double]) -> Double {
return values.reduce(0, combine: +)
}
postfix operator *>{}
postfix func *>(values:[Double]) -> Double {
return values.reduce(1, combine: *)
}
lists.map(*>)+>
let totalCombinations: [[Double]] = [
[2.4,1.45,3.35],
[2.4,1.45,1.42],
[2.4,3.35,1.42],
[1.45,3.35,1.42],
]
let result = totalCombinations.reduce(0.0) {$0 + $1.reduce(1.0) {$0 * $1} }
print(result) //->34.91405
但我不确定它是否“优雅”。
let a = [1.0, 2.0, 3.0]
let b = [4.0, 5.0, 6.0]
let c = [7.0, 8.0, 9.0, 10.0]
let d = [a, b, c]
let sum = d.reduce(0.0) { $0 + $1.reduce(1.0) {$0 * $1}}
print(sum) // prints 5166.0
*
运算符传递给reduce
($1.reduce(1, combine: *)
)。 - Hamish