ios - 在 Swift 中使用嵌套 reduce

标签 ios arrays swift functional-programming reduce

我有一个包含 Double 数组的数组,如屏幕截图所示:

enter image description here

我的目标是获取每个数组的 Double 元素相乘的总和。这意味着,我想乘以每个数组的所有元素,然后在我的例子中,我将有 3 个值,所以我得到它们的总和。

我想使用reduce, flatMap 吗?或任何优雅的解决方案。

我尝试了什么?

totalCombinations.reduce(0.0) { $0 + ($1[0]*$1[1]*$1[2])  }

但这只有在我知道包含 double 组的大小时才有效。

最佳答案

给定这些值

let lists: [[Double]] = [[1.1, 2.2, 3.3], [4.4, 5.5, 6.6]]

让我们来看看几种可能的方法

解决方案#1

let sum =  lists.reduce(0) { $0 + $1.reduce(1, combine: *) }

解决方案#2

如果你定义这个扩展

extension SequenceType where Generator.Element == Double {
    var product : Double { return reduce(1.0, combine: *) }
}

然后你就可以写了

let sum = lists.reduce(0) { $0 + $1.product }

解决方案#3

使用上面定义的扩展你也可以写

let sum = lists.map { $0.product }.reduce(0, combine:+)

解决方案 #4

如果我们定义这两个后缀运算符

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(*>)+>

关于ios - 在 Swift 中使用嵌套 reduce,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38634324/

相关文章:

c - (*pointer)[] 和 *pointer 有什么区别?

c# - 将具有零字符元素的字符数组转换为 C# 字符串

ios - 如何为 ImagePicker 制作圆形编辑区域而不是矩形?

ios - Xcode 更新到 7.3 后断言失败

ios - AVPlayer 在后台流式传输音频

c - 从函数中的 argv 分配指针

ios - 泛型 Obj-c 的 Swift 3 扩展无法访问类的泛型参数

swift - OSX/Swift 使应用程序可在任何地方使用

ios - Xcode 特征 View 不为零

ios - UILabel 不清除,覆盖以前的内容