TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

SOLVED: How to use enum and Predicate in a Query

Forums > SwiftUI

In the post How can I search in different columns in SwiftData Query? @ygeras pointed out to me that I should better use Enum for the values I use in the picker. I have now tried this to learn more, but fail in the init method.

I have implemented the following code to use enums:

The enum definition:

enum SearchColumns: Int, CaseIterable {
    case place = 1
    case chargingProvider = 2

    var description: String {
        switch self {
        case .place: return "Ort"
        case .chargingProvider: return "Provider"
        }
    }
}

In the "ChargingExpensesView" view:

@State private var searchColumn: SearchColumns = .place

var body: some View {
        NavigationStack {
            ChargingExpensesListingView(sort: sortOrder, searchString: searchText, searchColumn: searchColumn)
                .searchable(text: $searchText, prompt: "Suche in \(searchColumn.description)")
                .toolbar {

                    Menu("Suche in", systemImage: "magnifyingglass") {
                        Picker("Suche in", selection: $searchColumn) {
                            ForEach(SearchColumns.allCases, id: \.self) { searchColumn in
                                Text(searchColumn.description)
                                    .tag(searchColumn.rawValue)
                            }
                        }
                    }
                    .font1(size: 12)
                    .pickerStyle(.inline)
... 
...

The init method in "ChargingExpensesListingView":

Attempts 1:

 init(sort: SortDescriptor<ChargingExp>, searchString: String, searchColumn: SearchColumns) {
            _chargingExpenses = Query(filter: #Predicate {
                if searchString.isEmpty {
                    return true
                } else if searchColumn == .place {
                    return $0.place.localizedStandardContains(searchString)
                } else if searchColumn == .chargingProvider {
                        return $0.chargingProvider.localizedStandardContains(searchString)
                } else {
                    return true
                }
            }, sort: [sort])
        }

Here comes the error:

Member access without an explicit base is not allowed in this predicate

Attempts 2:

init(sort: SortDescriptor<ChargingExp>, searchString: String, searchColumn: SearchColumns) {
        _chargingExpenses = Query(filter: #Predicate {
            if searchString.isEmpty {
                return true
            } else {
                switch searchColumn {
                case .place where $0.place.localizedStandardContains(searchString):
                    return true
                case .chargingProvider where $0.chargingProvider.localizedStandardContains(searchString):
                    return true
                default:
                    return false
                }
            }
        }, sort: [sort])
    }

Here comes the error:

Switch expressions are not supported in this predicate

Does anyone have an idea what I'm doing wrong here, or is my whole enum approach incorrect? I am grateful for any tips.

2      

Hi @ralfb1105! Yesterday, I myself wanted to see who enums work in Predicate and it seems it is more pain than gain, well seems at the time being at least. Swift data is still quiet fresh so I guess this will change sooner or later. For me the reason to use enum in this particular case is to avoid typing in Strings as you may misspell it sooner or later. If you project contains not so many fields to search I guess you may go without using enums, but if projects starts to expand you may think of using enums in that case. As said above, with just two search options it maybe much easier to use just strings instead of enums.

3      

Hi @ygeras, thank you again for your assessment. If it's not so easy at the moment, then I'm reassured that I haven't made a big mistake in principle. For my app it is currently not necessary because I only have two fields, and I can easily make sure that I don't make any mistakes :-) I will certainly try it again later and maybe SwiftData and Swift will be ready by then so that it is a bit easier.

2      

On the second thought though, we can use enums ))) but initializing the search in slightly different way.

Let's assume you create enum as following but definitely change to your case:

enum SearchColumns {
    case name
    case details
}

Then create @State var to hold that value:

@State private var searchColumn = SearchColumns.name

Use Menu as previously but your way:

 Menu("Search in", systemImage: "magnifyingglass") {
                        Picker("Suche in", selection: $searchColumn) {
                            Text("Name")
                                .tag(SearchColumns.name)
                            Text("Details")
                                .tag(SearchColumns.details)
                        }
                        .pickerStyle(.inline)
                    }

Then pass the selection to your DestinationListingView as before:

DestinationListingView(sort: sortOrder, searchString: searchText, searchIn: searchColumn)

BUT THEN in the latter view you initialize it AS:

    init(sort: SortDescriptor<Destination>, searchString: String, searchIn: SearchColumns) {
        switch searchIn {
        case .name:
            _destinations = Query(filter: #Predicate {

                if searchString.isEmpty {
                    return true
                } else {
                    return $0.name.localizedStandardContains(searchString)
                }
            },sort: [sort])
        case .details:
            _destinations = Query(filter: #Predicate {
                if searchString.isEmpty {
                    return true
                } else {
                    return $0.details.localizedStandardContains(searchString)
                }
            },sort: [sort])
        }
    }

SO now you can use switch and can use enum without the need to utilize it with PREDICATE ))). Seems to be working just fine, did not check all use cases though!

3      

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.