UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Query filter error: Key path cannot refer to enum case

Forums > SwiftUI

Hey, I have a SwiftData model with enum. How can I filter the data in @Query by that enum?

I'm getting an error Key path cannot refer to enum case 'weekly'.

Model:

import Foundation
import SwiftData

enum BudgetPeriod: String, Codable {
    case weekly
    case monthly
    case yearly
}

@Model
final class Budget {
    var title: String
    var amount: Double
    var period: BudgetPeriod

    init(title: String, amount: Double, period: BudgetPeriod) {
        self.title = title
        self.amount = amount
        self.period = period
    }
}

View:

struct BudgetView: View {
    @Environment(\.modelContext) var modelContext

    @Query var budgets: [Budget]
    @Query(filter: #Predicate<Budget> { $0.period == BudgetPeriod.weekly }) var weeklyBudgets: [Budget]

    var body: some View {
        NavigationStack {
            List {
                ForEach(budgets) { budget in
                        HStack {
                            Text(budget.title)
                            Spacer()
                            Text("\(budget.amount, format: .currency(code: Locale.current.currency?.identifier ?? "USD"))")
                        }
                    }

                }
            }
            .navigationTitle("Budget")
        }
    }
}

#Preview {
    BudgetView()
}

3      

Hi,

Try making an init and storing the raw value in a constant:

@Environment(\.modelContext) var modelContext

@Query var budgets: [Budget]
@Query var weeklyBudgets: [Budget]

init() {
    let weekly = BudgetPeriod.weekly.rawValue

    let filter = #Predicate<Budget> { budget in
        budget.period.rawValue == weekly
    }

    _weeklyBudgets = Query(filter: filter)

}

4      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.