Sum of (double) fetch request field

穿精又带淫゛_ 提交于 2020-02-03 03:12:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!