什么是最简单(最好)的方法来找到一个数组的整数和在swift? 我有一个数组叫multiples我想知道这些倍数的和。
当前回答
斯威夫特3.0
我也有同样的问题,我在苹果的文档上找到了这个解决方案。
let numbers = [1, 2, 3, 4]
let addTwo: (Int, Int) -> Int = { x, y in x + y }
let numberSum = numbers.reduce(0, addTwo)
// 'numberSum' == 10
但是,在我的例子中,我有一个对象列表,然后我需要转换我的列表的值:
let numberSum = self.list.map({$0.number_here}).reduce(0, { x, y in x + y })
这对我很有用。
其他回答
这也是可行的:
let arr = [1,2,3,4,5,6,7,8,9,10]
var sumedArr = arr.reduce(0, combine: {$0 + $1})
print(sumedArr)
结果是:55
斯威夫特3、4、5
使用减少:
let totalamount = yourTransactionsModelArray.reduce(0) { $0 + $1.amount}
老式的理解方法:
for (var i = 0; i < n; i++) {
sum = sum + Int(multiples[i])!
}
//where n =数组中元素的个数
Swift3已更改为:
let multiples = [...]
sum = multiples.reduce(0, +)
保持简单……
var array = [1, 2, 3, 4, 5, 6, 7, 9, 0]
var n = 0
for i in array {
n += i
}
print("My sum of elements is: \(n)")
输出:
元素的和是:37
对我来说,这就像使用财产
let blueKills = match.blueTeam.participants.reduce(0, { (result, participant) -> Int in
result + participant.kills
})