【问题标题】:How to find sum of all objects for some key in array of custom objects in swift如何快速找到自定义对象数组中某个键的所有对象的总和
【发布时间】:2016-04-18 08:20:09
【问题描述】:

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

我在对象中有以下属性

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."

【问题讨论】:

    标签: ios arrays swift nsarray key-value-coding


    【解决方案1】:

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

    let totalAmount = duesArray.reduce(0.0) { $0 + ($1.dueAmount ?? 0) }
    
    print(totalAmount) // 4500.0
    

    【讨论】:

      【解决方案2】:

      问题是Double? 类型的属性没有暴露给Objective-C,因为Objective-C 不能处理非类类型的可选项。如果你把它改成var dueAmount: NSNumber?,就可以了。

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

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

      let totalAmount = duesArray.reduce(0.0) { $0 + ($1.dueAmount ?? 0.0) }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-07-14
        • 2019-08-02
        • 2021-08-17
        • 1970-01-01
        • 2016-06-20
        • 1970-01-01
        • 2015-09-16
        相关资源
        最近更新 更多