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

Sorting Core Data

Forums > SwiftUI

I have a project that uses Core Data. In my ViewListModel() that I call my functions . I want to sort my data in my ContentView() by using IOS 15 .searchable(). I have a published var filterWaypoints. In my ViewListModel() I have the following function:

func getAllWaypoints() {
        if filterWaypoints.isEmpty {
            let waypoints = CoreDataManager.shared.getAllWaypoints()
            DispatchQueue.main.async {
                self.waypoints = waypoints.map(WaypointViewModel.init)
            }
        } else {
            let waypoints = CoreDataManager.shared.getAllWaypoints()
            DispatchQueue.main.async {
                self.waypoints = waypoints.map(WaypointViewModel.init).filter { $0.name.lowercased().contains(self.filterWaypoints.lowercased()) }
            }
        }
    }

In this function I check if the search string is empty, and if it is, I just get the data. If the search string is not empty, it gets the data and it is sorted.

This works perfectly fine, and I am just wondering if there is a better way to do this.

3      

I am trying to understand your question. However I think you are confusing sorting with filtering?

Sorting is arranging your data in a specific order, perhaps by name, or date, or the height of your team's players.

Filtering, or selecting, is picking out data from your found set if it matches some criteria. Perhaps you only want to see albums released in November, or you want to list cooks who are expert bakers.

In either of these cases, I think you want to collect the search criteria, filter criteria, or the sorting criteria in your view. That's all the view should do. Collect the parameters. (If you have business logic in your view, you might want to review Paul's CoreData lessons.)

Then you want to pass those parameters into your model to find, filter, and sort your data. When the data set changes in your model, it should publish the changes. At this point your view will see that the published data changed, and then (and only then) it will update the view for your user.

3      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.