发现元素的总和斯威夫特阵列 [英] Finding sum of elements in Swift array
问题描述
这是最简单的(最好)的方式找到在迅速整数数组的总和?
我有一个数组称为倍数,我想知道的倍数的总和。谢谢你在前进!
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. Thank you in advance!
推荐答案
这是我能找到的最简单/最短的方法。
This is the easiest/shortest method I can find.
let multiples = [...]
sum = multiples.reduce(0, combine: +)
一些更多的信息:
Some more info:
本使用Array的降低方法(文档<一个href=\"https://developer.apple.com/library/$p$prelease/ios/documentation/Swift/Reference/Swift_SequenceType_Protocol/index.html#//apple_ref/swift/intfm/SequenceType/s:FeRq_Ss12SequenceType_SsS_6reduceu__Rq_S__Fq_FzTqd__7combineFzTqd__qqq_S_9GeneratorSs13GeneratorType7Element_qd___qd__\">here),它允许你通过递归应用提供封闭元素的集合减少到一个单一的价值。我们给它0作为初始值,然后,从本质上讲,封闭 {$ 0 + $ 1}
。当然,我们可以简化到一个加号,因为这是如何斯威夫特卷。
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.
这篇关于发现元素的总和斯威夫特阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!