I am new to SwiftUI and GRDB (using it for a school project), I have been struggling to store subclasses in my database.
This is my code:
class Item: Identifiable, Codable, Hashable, MutablePersistableRecord, FetchableRecord {
// Defining properties
var id = UUID().uuidString
var name: String = ""
var description: String = ""
var dueDate: Date?
var isCompleted: Bool = false
var dateType: DateType = .due
var color: PriorityColor = .none
var tagID: String?
// Initialisation of Item
init(id: String = UUID().uuidString, name: String, description: String, dueDate: Date? = nil, isCompleted: Bool, dateType: DateType, color: PriorityColor, tag: Tag? = nil) {
self.id = id
self.name = name
self.description = description
self.dueDate = dueDate
self.isCompleted = isCompleted
self.dateType = dateType
self.color = color
self.tagID = tag?.id
}
// Conforming to Hashable and Equatable protocols
func hash(into hasher: inout Hasher) {
hasher.combine(self.id)
}
static func ==(lhs: Item, rhs: Item) -> Bool {
return lhs.id == rhs.id
}
}
// MARK: Enums for Item
extension Item {
enum DateType: String, Codable, CaseIterable, Identifiable, DatabaseValueConvertible {
case due = "Due" // The item is due on DueDate
case completeBy = "Complete by" // The item should be marked as completed by DueDate
case noDate = "No Date"
var id: Self { self }
}
enum PriorityColor: String, Codable, CaseIterable, Identifiable, DatabaseValueConvertible {
case red
case yellow
case green
case none = "No Colour"
var id: Self { self }
var name: String { rawValue.localizedCapitalized }
var color: Color {
switch self {
case .red:
return .red
case .yellow:
return .yellow
case .green:
return .green
default:
return .gray
}
}
var icon: String {
switch self {
case .red:
return "exclamationmark.3"
case .yellow:
return "exclamationmark.2"
case .green:
return "exclamationmark"
default:
return "nosign"
}
}
}
}
extension Item: TableRecord {
static let tagRelation = belongsTo(Tag.self)
}
class TaskItem: Item {
// Initialisation of TaskItem
override init(
id: String = UUID().uuidString,
name: String,
description: String,
dueDate: Date? = nil,
isCompleted: Bool = false,
dateType: DateType = .due,
color: PriorityColor = .none,
tag: Tag? = nil
) {
super.init(id: id, name: name, description: description, dueDate: dueDate, isCompleted: isCompleted, dateType: dateType, color: color, tag: tag)
}
}
I am getting a 'required' initializer 'init(from:)' must be provided by subclass of 'Item'
error in the TaskItem definition, and I'm not sure how best to fix it. It looks like I need to handle the encoding and decoding myself but it doesn't seem to work correctly. How do I do it correctly?
Thank you!