Arasuvel - 1 year ago 123

Swift Question

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

Answer Source

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
```