有一个名为 Item 的实体,它有一个名为 amount 的 Double 属性,向你的 View 添加一个计算属性:
Code:
struct ContentView: View {@Environment(\.managedObjectContext) private var viewContext@FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \Item.timestamp, ascending: true)],animation: .default)private var items: FetchedResults<Item>var totalAmount: Double {items.reduce(0) { $0 + $1.amount }}var body: some View {List {ForEach(items) { item inHStack {Text("Item \(item.name!)")Spacer()Text("\(item.amount)")}}Divider()Text("Total Amount: \(totalAmount)")}}
}