Using ActiveRecord with SwiftData
Everything is simple and SwiftUI + UnitTest friendly. Remember that we can use SwiftData data in memory, not only in disk. Also we can use it for Web Service data requests creating a ”manager object” to sync Web Service data with our local data.
@Model
class Recipe {
var name: String
var description: String
var ingredients: [Ingredient]
var steps: [String]
}
// Creating data (factory methods)
extension Recipe {
static var myFavorite: Self { ... }
static var top30GordonRamsayRecipes: [Self] { ... }
static func chatGPTSuggestion(text: String) -> Self { ... }
}
// Loading data (factory fetch descriptors)
extension Recipe {
// @Query(Recipe.allRecipes) private var recipes: [Recipe] // Managed by SwiftUI
// let recipes = try context.fetch(Recipe.allRecipes) // Managed by developer
static var allRecipes: FetchDescriptor<Self> { ... }
static var healthyRecipes: FetchDescriptor<Self> { ... }
static func recipesWithIngredients(_ ingredients: [Ingredient]) -> FetchDescriptor<Self> { ... }
}
// Updating data
extension Recipe {
func addSuggestedCondiments() { ... }
func replaceUnhealthyIngredients() { ... }
func reduceCaloriesByReduceOrReplaceIngredients(maxCalories: Double) { ... }
func insert(context: ModelContext) { ... }
func delete(context: ModelContext) { ... }
}
// Information
extension Recipe {
var totalCalories: Double { ... }
var isHealthy: Bool { ... }
}
---
@Model
class Ingredient { ... }
We can have one Recipe file:
Recipe.swift // Object + Tasks
Two Recipe files, if needed:
Recipe.swift // Object
Recipe+Tasks.swift // Tasks
The files we need for Recipe:
Recipe.swift // Object
Recipe+Creating.swift // Creating tasks
Recipe+Loading.swift // Loading tasks
Recipe+Updating.swift // Updating tasks
Recipe+Information.swift // Information tasks
Topic:
UI Frameworks
SubTopic:
SwiftUI
Tags: