Ara*_*vel 1 arrays key-value-coding nsarray ios swift
我有一些对象,我需要在其中找到特定键的总和.
我在对象中有以下属性
class Due: NSObject {
var dueIndex: Int?
var dueAmount: Double?
}
Run Code Online (Sandbox Code Playgroud)
我有以下逻辑将对象添加到数组
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)
}
Run Code Online (Sandbox Code Playgroud)
在此之后,我需要将duesArray中的所有值与key dueAmount相加.请告诉我如何使用KVC实现它.
我试过使用下面的行.
print((duesArray as AnyObject).valueForKeyPath("@sum.dueAmount")).
Run Code Online (Sandbox Code Playgroud)
得到以下错误
failed: caught "NSUnknownKeyException", "[Due 0x7ff9094505d0> valueForUndefinedKey:]: this class is not key value coding-compliant for the key dueAmount."
Run Code Online (Sandbox Code Playgroud)
Een*_*dje 15
如果你只想要dueAmount你duesArray的类型的总和Due那么你可以简单地使用reduce():
let totalAmount = duesArray.reduce(0.0) { $0 + ($1.dueAmount ?? 0) }
print(totalAmount) // 4500.0
Run Code Online (Sandbox Code Playgroud)