I have used core data before via the model editor. This is the first time I'm using swift data and that too with CloudKit. Can you tell me if the following model classes are correct?
I have an expense which can have only one sub category which in turn belongs to a single category. Here are my classes...
// Expense.swift
// Pocket Expense Diary
//
// Created by Neerav Kothari on 16/05/25.
//
import Foundation
import SwiftData
@Model
class Expense {
@Attribute var expenseDate: Date? = nil
@Attribute var expenseAmount: Double? = nil
@Attribute var expenseCategory: Category? = nil
@Attribute var expenseSubCategory: SubCategory? = nil
var date: Date {
get {
return expenseDate ?? Date()
}
set {
expenseDate = newValue
}
}
var amount: Double{
get {
return expenseAmount ?? 0.0
}
set {
expenseAmount = newValue
}
}
var category: Category{
get {
return expenseCategory ?? Category.init(name: "", icon: "")
}
set {
expenseCategory = newValue
}
}
var subCategory: SubCategory{
get {
return expenseSubCategory ?? SubCategory.init(name: "", icon: "")
}
set {
expenseSubCategory = newValue
}
}
init(date: Date, amount: Double, category: Category, subCategory: SubCategory) {
self.date = date
self.amount = amount
self.category = category
self.subCategory = subCategory
}
}
//
// Category.swift
// Pocket Expense Diary
//
// Created by Neerav Kothari on 16/05/25.
//
import Foundation
import SwiftData
@Model
class Category {
@Attribute var categoryName: String? = nil
@Attribute var categoryIcon: String? = nil
var name: String {
get {
return categoryName ?? ""
}
set {
categoryName = newValue
}
}
var icon: String {
get {
return categoryIcon ?? ""
}
set {
categoryIcon = newValue
}
}
@Relationship(inverse: \Expense.expenseCategory) var expenses: [Expense]? = []
init(name: String, icon: String) {
self.name = name
self.icon = icon
}
}
// SubCategory.swift
// Pocket Expense Diary
//
// Created by Neerav Kothari on 16/05/25.
//
import Foundation
import SwiftData
@Model
class SubCategory {
@Attribute var subCategoryName: String? = nil
@Attribute var subCategoryIcon: String? = nil
var name: String {
get {
return subCategoryName ?? ""
}
set {
subCategoryName = newValue
}
}
var icon: String {
get {
return subCategoryIcon ?? ""
}
set {
subCategoryIcon = newValue
}
}
@Relationship(inverse: \Expense.expenseSubCategory) var expenses: [Expense]? = []
init(name: String, icon: String) {
self.name = name
self.icon = icon
}
}
The reason why I have wrappers is the let the existing code (before CloudKit was integrated), work.
In future versions I plan to query expenses even via category or sub category. I particularly doubt for the relationship i have set. should there be one from category to subcategory as well?