什么是最简单(最好)的方法来找到一个数组的整数和在swift? 我有一个数组叫multiples我想知道这些倍数的和。
当前回答
Swift 4示例
class Employee {
var salary: Int = 0
init (_ salary: Int){
self.salary = salary
}
}
let employees = [Employee(100),Employee(300),Employee(600)]
var sumSalary = employees.reduce(0, {$0 + $1.salary}) //1000
其他回答
保持简单……
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
Swift3已更改为:
let multiples = [...]
sum = multiples.reduce(0, +)
这也是可行的:
let arr = [1,2,3,4,5,6,7,8,9,10]
var sumedArr = arr.reduce(0, combine: {$0 + $1})
print(sumedArr)
结果是:55
用于对象数组中元素的和
self.rankDataModelArray.flatMap{$0.count}.reduce(0, +)
对我来说,这就像使用财产
let blueKills = match.blueTeam.participants.reduce(0, { (result, participant) -> Int in
result + participant.kills
})