Skip to content

Instantly share code, notes, and snippets.

@colinfwren
Last active January 18, 2025 22:39
Show Gist options
  • Save colinfwren/06168dc98d4ea59f2a9ea235e589a089 to your computer and use it in GitHub Desktop.
Save colinfwren/06168dc98d4ea59f2a9ea235e589a089 to your computer and use it in GitHub Desktop.
An example of the Service pattern in Swift
import SwiftData
// Ensure the service conforms to the ObservableObject protocol
class ExampleService: ObservableObject {
private let modelContext: ModelContext
@Published var someList = [SomeModel]() // The published decorator for properties that should trigger SwiftUI updates
// Pass the modelContext in to the initialiser so can use dependency injection during testing
init(modelContext: ModelContext) {
self.modelContext = modelContext
// On init, go populate the initial someList value by fetching the records
fetchData()
}
func someComplexMultiModelAction() {
let someOtherRecordDescriptor = FetchDescriptor<SomeOtherModel>(sortBy: [SortDescriptor(\SomeOtherModel.created, order: .reverse)])
do {
if let someOtherRecord = try self.modelContext.fetch(someOtherRecordDescriptor).first {
let someNewListItem = SomeModel(name: "New Thing", otherModelInstance: someOtherRecord)
self.modelContext.insert(someNewListItem)
fetchData()
} else {
// handle no existing Some Other Record
let someOtherRecord = SomeOtherModel(name: "A new other record to reference")
let someNewListItem = SomeModel(name: "New Thing", otherModelInstance: someOtherRecord)
self.modelContext.insert(someNewListItem)
fetchData()
}
} catch {
// error handling
}
}
func fetchData() {
do {
let descriptor = FetchDescriptor<SomeModel>()
someList = try self.modelContext.fetch(descriptor)
} catch {
someList = []
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment