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

使用减少:

let totalamount = yourTransactionsModelArray.reduce(0) { $0 + $1.amount}

老式的理解方法:

for (var i = 0; i < n; i++) {
 sum = sum + Int(multiples[i])!
}

//where n =数组中元素的个数

Swift 3+一行求和对象的属性

var totalSum = scaleData.map({$0.points}).reduce(0, +)

哪里点的属性在我的自定义对象scaleData,我试图减少

对我来说,这就像使用财产

    let blueKills = match.blueTeam.participants.reduce(0, { (result, participant) -> Int in
        result + participant.kills
    })

这是我能找到的最简单/最短的方法。

Swift 3和Swift 4:

let multiples = [...]
let sum = multiples.reduce(0, +)
print("Sum of Array is : ", sum)

斯威夫特2:

let multiples = [...]
sum = multiples.reduce(0, combine: +)

更多信息:

这使用了Array的reduce方法(这里有文档),该方法允许你“通过递归应用提供的闭包将元素集合减少到单个值”。我们给它0作为初始值,然后,本质上,闭包{$0 + $1}。当然,我们可以将其简化为一个加号,因为Swift就是这样运行的。

另一种简单的方法:

let sumOfMultiples = ar.reduce(0) { x, y in x + y }          
print(sumOfMultiples)