什么是最简单(最好)的方法来找到一个数组的整数和在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

其他回答

斯威夫特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 })

这对我很有用。

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
    })

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