Post

Replies

Boosts

Views

Activity

Reply to SwiftData Aggregation
import SwiftData @Model public class Person { var name: String var age: Int init(name: String, age: Int) { self.name = name self.age = age } } You'll probably want to do the below differently. The below ViewController is just given to you for ideas. import UIKit import SwiftData class ViewController: UIViewController { var container: ModelContainer? var context: ModelContext? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. do { let schema = Schema([Person.self]) let modelConfig = ModelConfiguration(schema: schema, cloudKitDatabase: .private("iCloud.com.yourcompany.ClassStats")) container = try ModelContainer(for: schema, configurations: [modelConfig]) if let container = container { context = ModelContext(container) context?.autosaveEnabled = true } } catch { print(error) } } func getStats() { let minAge = 20 let maxAge = 40 let predicate = #Predicate<Person> { person in person.age >= minAge && person.age <= maxAge } let sortBy = [SortDescriptor<Person>(\.name)] var descriptor = FetchDescriptor<Person>(predicate: predicate, sortBy: sortBy) if let persons = try? context?.fetch(descriptor), persons.count > 0 { let count = persons.count } } }
Aug ’23