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


当前回答

在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 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就是这样运行的。

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

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

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

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
@IBOutlet var valueSource: [MultipleIntBoundSource]!

private var allFieldsCount: Int {
    var sum = 0
    valueSource.forEach { sum += $0.count }
    return sum
}

用于嵌套参数

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

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