TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

SwiftData preview crash when adding a second model

Forums > SwiftUI

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
    }
}

2      

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.