什么是最简单(最好)的方法来找到一个数组的整数和在swift? 我有一个数组叫multiples我想知道这些倍数的和。


当前回答

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

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

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

其他回答

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

这对我很有用。

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

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

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

保持简单……

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中,您还可以将序列元素约束为Numeric协议,以返回序列中所有元素的和,如下所示

extension Sequence where Element: Numeric {
    /// Returns the sum of all elements in the collection
    func sum() -> Element { return reduce(0, +) }
}

编辑/更新:

Xcode 10.2•Swift 5或更高版本

我们可以简单地将序列元素约束到新的additive算术协议,以返回集合中所有元素的和

extension Sequence where Element: AdditiveArithmetic {
    func sum() -> Element {
        return reduce(.zero, +)
    }
}

Xcode 11•Swift 5.1或更高版本

extension Sequence where Element: AdditiveArithmetic {
    func sum() -> Element { reduce(.zero, +) }
}

let numbers = [1,2,3]
numbers.sum()    // 6

let doubles = [1.5, 2.7, 3.0]
doubles.sum()    // 7.2

要对自定义对象的一个属性求和,我们可以扩展Sequence以接受一个谓词来返回一个符合additive算术的值:

extension Sequence  {
    func sum<T: AdditiveArithmetic>(_ predicate: (Element) -> T) -> T { reduce(.zero) { $0 + predicate($1) } }
}

用法:

struct Product {
    let id: String
    let price: Decimal
}

let products: [Product] = [.init(id: "abc", price: 21.9),
                           .init(id: "xyz", price: 19.7),
                           .init(id: "jkl", price: 2.9)
]

products.sum(\.price)  // 44.5

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