问题
Is it possible to get the sum of a core data (through a fetch request) field (double) in Swift UI? Thanks in advance.
回答1:
Yes, you could use the reduce
method.
var sum: Double {
fetchRequest.reduce(0) { $0 + $1.number }
}
This starts with an initial value of 0, and for each item in the FetchRequest, it adds the number
property to the accumulated total.
Assuming you have an entity called SomeEntity
in your .xcdatamodeld file, with an attribute called number
, the whole code might look like
struct ContentView: View {
@Environment(\.managedObjectContext) var managedObjectContext
@FetchRequest(entity: SomeEntity.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \SomeEntity.number, ascending: false)]) var fetchRequest: FetchedResults<SomeEntity>
var sum: Double {
fetchRequest.reduce(0) { $0 + $1.number }
}
var body: some View {
Form {
Section {
Button("Add number") {
let entity = SomeEntity(context: self.managedObjectContext)
entity = Double.random(in: 0...10)
try? self.managedObjectContext.save()
}
}
Section(header: Text("Sum")) {
Text("\(sum)")
}
Section {
ForEach(fetchRequest, id: \.self) {
Text("\($0.number)")
}
}
}
}
}
来源:https://stackoverflow.com/questions/58956207/sum-of-double-fetch-request-field