I am trying to loop through my Core Data Database to get all the prices of all the Items but I’m getting the error, Value of type ‘FetchedResults.Element’ (aka ‘Item’) has no member ‘price2pay’ below is my CartView.swift. Would someone please assist me on how to fix this?
//
// CartView.swift
// PonnasKitchen
//
// Created by Sricharan Ponna on 02/08/2024.
// Copyright © 2024 Sricharan Ponna. All rights reserved.
//
import SwiftUI
func forLoop() {
@FetchRequest(sortDescriptors: []) var checkout: FetchedResults<Item>
@Environment(.managedObjectContext) var moc
var subTotal: Int32 = 0
do {
for i in checkout {
subTotal = try! i.price2pay + subTotal // Error is here
}
}
}
struct CartView: View {
@FetchRequest(sortDescriptors: []) var checkout: FetchedResults<Item>
@Environment(.managedObjectContext) var moc
@State var subTotal: Int32 = 0
@State var productPrices: [Int32] = []
var body: some View {
NavigationStack {
List {
ForEach(checkout) { product in
VStack(alignment: .leading, spacing: 8) {
Text((product.name ?? "Chicken Biryani"))
.font(.system(size: 20, design: .rounded).bold())
Text("Quantity: (product.qty)")
.font(.callout.bold())
Text("Price of Each: £(Int32(product.price))")
.font(.callout.bold())
Text("Price to pay: £(product.price2Pay)")
.font(.callout.bold())
}
.swipeActions {
Button(role: .destructive) {
do {
let item2Delete = try moc.existingObject(with: product.objectID)
moc.delete(item2Delete)
Task(priority: .background) {
try await moc.perform {
try moc.save()
}
}
} catch {
print(error)
}
} label: {
Label("Delete", systemImage: "trash.fill")
}
}
.frame(maxWidth: .infinity, alignment: .leading)
}
}
HStack() {
Text("Subtotal: ")
.padding(.horizontal)
Spacer()
Text("£(subTotal).00")
.padding(.horizontal)
Spacer()
NavigationLink(destination: PurchaseView()) {
HStack {
Image(systemName: "creditcard.and.123")
.symbolVariant(.fill)
Divider()
.padding(.vertical, 8)
Text("Proceed to Buy")
}
.frame(minWidth: 150, maxHeight: 55)
.background(.mint)
.foregroundColor(.white)
.clipShape(RoundedRectangle(cornerRadius: 8))
}
}
}
.navigationTitle("Checkout")
}
}
struct ItemCardView: View {
var body: some View {
HStack {
Text("card")
.font(.system(size: 25))
}
}
}
//struct CartTitleView: View {
//
// var body: some View {
// VStack(content: {
// Text("Cart")
// .font(.title2)
// .fontWeight(.heavy)
// })
// }
//}
#Preview {
CartView()
}
I am trying to loop through my Core Data Database to get all the prices of all the Items but I’m getting the error, Value of type ‘FetchedResults.Element’ (aka ‘Item’) has no member ‘price2pay’ below is my CartView.swift. Would someone please assist me on how to fix this?
Sricharan Ponna is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.