1

I have array of objects in which I need to find sum of the particular key.

I have the following properties in object

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

I have the following logic to add the objects to array

   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)
    }

After this I need the sum all the values in duesArray for key dueAmount. Please let me know how to achieve it using KVC.

I have tried by using following below line.

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

Got the following error

failed: caught "NSUnknownKeyException", "[Due 0x7ff9094505d0> valueForUndefinedKey:]: this class is not key value coding-compliant for the key dueAmount."
Arasuvel
  • 2,971
  • 1
  • 25
  • 40

2 Answers2

17

If you just want the sum of dueAmount in your duesArray with type Due then you can simply use reduce():

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

print(totalAmount) // 4500.0
Eendje
  • 8,815
  • 1
  • 29
  • 31
2

The problem is that the property of type Double? is not exposed to Objective-C because Objective-C can't handle non-class-type optionals. If you change it to var dueAmount: NSNumber?, it works.

That begs the question why dueAmount and dueIndex are optionals in the first place. Must they be?

As Eendje mentioned, the Swift way of doing this is to use reduce:

let totalAmount = duesArray.reduce(0.0) { $0 + ($1.dueAmount ?? 0.0) }
Ole Begemann
  • 135,006
  • 31
  • 278
  • 256