什么是最简单(最好)的方法来找到一个数组的整数和在swift? 我有一个数组叫multiples我想知道这些倍数的和。
当前回答
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
})
保持简单……
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
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 =数组中元素的个数
斯威夫特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 })
这对我很有用。