Search code examples
swiftswiftdata

How to loop through data in a SwiftData model


I am trying to loop through data saved in a SwiftData model in a function, do some cleanup and selective add that data to a different SwiftData model. I can't seem to figure out how to do this basic loop through via swift. I don't want to do this in a list on a screen but by a function I can trigger to run against the data. Here is what I've tried but

func updateTripData() {
    @Environment(\.modelContext) var modelContext
    @Query var locationDataSD: [LocationDataSD]
    
    var locations: [LocationDataSD]
    var index = 0
    while index < locations.count {
        print(locations[index].timestamp, locations[index].latitude, locations[index].latitude)
    }
}

I get an error

Cannot find '_locationDataSD' in scope

Solution

  • If you want to access SwiftData outside of a view in a function then you need to pass a ModelContext (or ModelContainer) object to that function since you cannot use property wrappers like @Environment and @Query outside of a view.

    And since you can't use @Query you will need to use a FetchDescriptor when fetching data.

    func updateTripData(using context: ModelContext) throws {
        let fetchDescriptor = FetchDescriptor<LocationDataSD>()
        let locations = try context.fetch(fetchDescriptor)
    
        for location in locations {
            //perform updates
        }
    }
    

    If you like minimised code the above can be written as

    try context.fetch(FetchDescriptor<LocationDataSD>()).forEach { location in
         //perform updates
    }