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


当前回答

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

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

其他回答

另一种简单的方法:

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

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

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

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

斯威夫特3

如果你有一个通用对象的数组,你想对一些对象属性求和,那么:

class A: NSObject {
    var value = 0
    init(value: Int) {
       self.value = value
    }
}

let array = [A(value: 2), A(value: 4)]      
let sum = array.reduce(0, { $0 + $1.value })
//                           ^       ^
//                        $0=result  $1=next A object
print(sum) // 6 

尽管for-cycle的形式较短,但很多时候你可能更喜欢经典的for-cycle:

let array = [A(value: 2), A(value: 4)]
var sum = 0
array.forEach({ sum += $0.value}) 
// or
for element in array {
   sum += element.value
}
@IBOutlet var valueSource: [MultipleIntBoundSource]!

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

用于嵌套参数

在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