我试图在Swift中添加一些自定义对象中找到的值。我在Playground中使用以下代码:
//Custom Object
class EntryPack: NSObject{
var date: String!
var duration: Double!
var customValues:[CustomValuePack] = [] //Nested array of objects declared below
}
//Another object to nest in the above
class CustomValuePack: NSObject{
var name:String!
var value: Double!
}
//Instantiate nested objects
let cv1 = CustomValuePack()
cv1.name = "Day"
cv1.value = 1.2
let cv2 = CustomValuePack()
cv2.name = "Day"
cv2.value = 1.3
let cv3 = CustomValuePack()
cv2.name = "Night"
cv2.value = 2.2
//Instantiate parent objects
let entry1 = EntryPack()
entry1.date = "bingo"
entry1.duration = 1.1
entry1.customValues = [cv1, cv2]
let entry2 = EntryPack()
entry2.date = "bingo"
entry2.duration = 2.2
let entry3 = EntryPack()
entry3.date = "dang"
entry3.duration = 3.0
//Throw it all together into an array
var package = [entry1, entry2, entry3]
//Predicate for some filtering
let predicate = NSPredicate(format:"date = %@", "bingo")
let results = (package as NSArray).filteredArrayUsingPredicate(predicate) as! [EntryPack]
//Sum all the parent object durations
let sum = results.reduce(0.0) { $0 + $1.duration }
print(sum) // = 3.3
但现在我想为value
为CustomValuePack
的每个name
添加"Day"
。
我无法弄清楚如何对嵌套的对象数组进行类似的缩减。我尝试过类似的东西,但会产生语法错误:
let sum2 = results.reduce(0.0) { $0.customValues + $1.customValues.value } //Error
如何对嵌套的对象数组中的值求和?我最终还想应用NSPredicate来按name = Day
进行过滤,但我不是那么远爱好。
答案 0 :(得分:2)
鉴于MOVE FUNCTION NUMVAL(WS-VALUE) TO WS-VALUE-INTERNAL
定义如下
entries
您可以使用名称==" Day"提取CustomValues。并使用此代码
对值字段求和let entries = [entry1, entry2, entry3]
您正在使用Swift,但出于某种原因,您的代码中仍然存在大量Objective-C。
这就是我重构代码的方式
let sum = entries
.flatMap { $0.customValues }
.filter { $0.name == "Day" }
.map { $0.value }
.reduce(0, combine: +)
请注意,现在
struct EntryPack { let date: String let duration: Double let customValues:[CustomValuePack] } struct CustomValuePack { let name:String let value: Double } let cv1 = CustomValuePack(name: "Day", value: 1.2) let cv2 = CustomValuePack(name: "Day", value: 1.3) let cv3 = CustomValuePack(name: "Night", value: 2.2) let entry1 = EntryPack(date: "bingo", duration: 1.1, customValues: [cv1, cv2]) let entry2 = EntryPack(date: "bingo", duration: 2.2, customValues: []) let entry3 = EntryPack(date: "dang", duration: 3.0, customValues: [])
和EntryPack
是值类型的结构。