Hi, why is my preview crashing when adding category to a transaction with exampleTransaction.category = exampleCategory
?
Is there any good source where can I learn more about SwiftData and Previews? I'm really lost in Apple docs.
#Preview {
do {
let config = ModelConfiguration(isStoredInMemoryOnly: true)
let container = try ModelContainer(for: Transaction.self, configurations: config)
let exampleCategory = Category(title: "Salary", icon: "banknote", color: "#00ff00", budgetType: BudgetType.fixed)
var exampleTransaction = Transaction(amount: 2836.76, date: .now, notes: "", isIncome: true)
exampleTransaction.category = exampleCategory
return TransactionRowView(transaction: exampleTransaction)
.modelContainer(container)
} catch {
fatalError("Failed to create model container.")
}
}
Category model:
import Foundation
import SwiftData
enum BudgetType: String, Codable {
case fixed
case flexible
case savings
}
@Model
final class Category {
var title: String
var icon: String
var color: String
var budgetType: BudgetType
var transactions = [Transaction]()
init(title: String, icon: String, color: String, budgetType: BudgetType) {
self.title = title
self.icon = icon
self.color = color
self.budgetType = budgetType
}
}
Transaction model:
import Foundation
import SwiftData
@Model
final class Transaction {
var amount: Double
var date: Date
var notes: String
var isIncome: Bool
var category: Category?
init(amount: Double, date: Date, notes: String, isIncome: Bool) {
self.amount = amount
self.date = date
self.notes = notes
self.isIncome = isIncome
}
}