如何找到 swift 中自定义对象数组中某个键的所有对象的总和

How to find sum of all objects for some key in array of custom objects in swift

我有一个对象数组,我需要在其中找到特定键的总和。

我在对象中有以下属性

class Due: NSObject {
var dueIndex: Int?
var dueAmount: Double?
}

我有以下逻辑将对象添加到数组

   var duesArray = [Due]()

    for i in 0..<10 {
        let dueObject = NDDue();
        // Update the due object with the required data.
        dueObject.dueIndex = i
        dueObject.dueAmount = 100 * i

        // Add the due object to dues array.
        duesArray.append(dueObject)
    }

在此之后,我需要将 duesArray 中的所有值相加作为键 dueAmount。请告诉我如何使用 KVC 实现它。

我已经尝试使用以下行。

print((duesArray as AnyObject).valueForKeyPath("@sum.dueAmount")).

出现以下错误

failed: caught "NSUnknownKeyException", "[Due 0x7ff9094505d0> valueForUndefinedKey:]: this class is not key value coding-compliant for the key dueAmount."

如果您只想要 duesArray 中类型为 DuedueAmount 的总和,那么您可以简单地使用 reduce():

let totalAmount = duesArray.reduce(0.0) { [=10=] + (.dueAmount ?? 0) }

print(totalAmount) // 4500.0

问题是 Double? 类型的 属性 没有暴露给 Objective-C 因为 Objective-C 无法处理非 class 类型选项。如果将其更改为 var dueAmount: NSNumber?,它会起作用。

这就引出了一个问题,为什么 dueAmountdueIndex 首先是可选的。一定是吗?

正如 Eendje 提到的,Swift 方法是使用 reduce:

let totalAmount = duesArray.reduce(0.0) { [=10=] + (.dueAmount ?? 0.0) }