查找 Swift 数组中元素的总和 [英] Finding sum of elements in Swift array
问题描述
在 swift 中找到整数数组的总和的最简单(最佳)方法是什么?我有一个名为 multiples 的数组,我想知道倍数的总和.
What is the easiest (best) way to find the sum of an array of integers in swift? I have an array called multiples and I would like to know the sum of the multiples.
推荐答案
这是我能找到的最简单/最短的方法.
This is the easiest/shortest method I can find.
Swift 3 和 Swift 4:
Swift 3 and Swift 4:
let multiples = [...]
let sum = multiples.reduce(0, +)
print("Sum of Array is : ", sum)
斯威夫特 2:
let multiples = [...]
sum = multiples.reduce(0, combine: +)
<小时>
更多信息:
Some more info:
这使用了 Array 的 reduce 方法(文档 here),这允许您通过reduce提供的单个值集合向下还原提供的元素.我们给它 0 作为初始值,然后基本上是闭包 { $0 + $1 }
.当然,我们可以将其简化为一个加号,因为这就是 Swift 滚动的方式.
This uses Array's reduce method (documentation here), which allows you to "reduce a collection of elements down to a single value by recursively applying the provided closure". We give it 0 as the initial value, and then, essentially, the closure { $0 + $1 }
. Of course, we can simplify that to a single plus sign, because that's how Swift rolls.
这篇关于查找 Swift 数组中元素的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!