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.