Don’t over-engineering! No suggested architecture for SwiftUI, just MVC without the C.
On SwiftUI you get extra (or wrong) work and complexity for no benefits. Don’t fight the system.
Don’t over-engineering! No suggested architecture for SwiftUI, just MVC without the C.
On SwiftUI you get extra (or wrong) work and complexity for no benefits. Don’t fight the system.
One of the solution is to put domain logic right inside the SwiftData model. This is shown below:
@Model class BudgetCategory {
@Attribute(.unique) var title: String = ""
var amount: Decimal = 0.0
@Relationship(deleteRule: .cascade) var transactions: [Transaction] = []
init(title: String, amount: Decimal) {
self.title = title
self.amount = amount
}
// exists function to check if title already exist or not
private func exists(context: ModelContext, title: String) -> Bool {
let predicate = #Predicate<BudgetCategory> { $0.title == title }
let descriptor = FetchDescriptor(predicate: predicate)
do {
let result = try context.fetch(descriptor)
return !result.isEmpty ? true: false
} catch {
return false
}
}
func save(context: ModelContext) throws {
// find if the budget category with the same name already exists
if !exists(context: context, title: self.title) {
// save it
context.insert(self)
} else {
// do something else
throw BudgetCategoryError.titleAlreadyExist
}
}
}
Source: https://azamsharp.com/2023/07/04/the-ultimate-swift-data-guide.html
You can also watch my video on SwiftData Testing Domain Models. https://www.youtube.com/watch?v=OF7TLbMu1ZQ&t=389s
I stared working on an open source project called "HelloMarket". It is an E-Commerce application using SwiftUI, ExpressJS and Postgres database. Currently, it is in development phase but you can explore the repository.
@Appeloper I know that this is a pretty old thread. But this is interesting.
So basically a Store is just an observed Repository then? It's not even a VM. Because a VM is also handling the state of a view such as error handling when the fetching / updating the model (ie. should we display a Toast or Alert or a fullscreen View, what error message to show, the color scheme, the callback when the alert or view is closed, etc). Or when to display or hide activity indicator. Etc. A VM is per view controller / feature while from what I've seen so far, a Store is just per model. So where do you put these other logics? On the corresponding Views? So that means the Views will hold both the layout logic and some business logic? CMIIW.