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

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.