How could one take a data model with nested types (like the one below) and have the data stored in a document? Thanks.
class ContentCell {
var isMarkedOff: Bool = false
var cellText: String = ""
}
class CellRow {
var RowCells: [ContentCell] = [ContentCell(), ContentCell(), ContentCell()]
}
class FullChart {
var ChartRows: [CellRow] = [CellRow()]
}
I think I may have found a solution, (or rather, realized a had been missing it), but some related code (specified blow) seems to cause an error to be thrown, so I can't test it. The code syntax is straight from an Apple tutorial, so it might be outdated.
import SwiftUI
import UniformTypeIdentifiers
import CoreServices
@main
struct Test_ProjectApp: App {
var body: some Scene {
DocumentGroup(newDocument: Test_ProjectDocument()) { file in
ContentView(document: file.$document)
}
}
}
////
extension UTType {
static let Test_ProjectDocument =
UTType(exportedAs: "com.testproject")
}
struct Test_ProjectDocument: FileDocument, Codable { // < Type conformance error is thrown, seemingly because the type checker wants the fileWrapper stuff (bellow) in a different syntax.
// The FileDocument struct can have properties defined, and initialized here: //
var fullTable: [CellRow] // < Each CellRow instance is saved in this array ("fullTable").
// The type "CellRow" can have properties which are arrays of other types.
init() {
self.fullTable = [] // < empty array. Start items can be defined inside.
}
//
static var readableContentTypes: [UTType] { [.Test_ProjectDocument] }
// These don't seem to work as in the tutorial "Building Document Based Apps With swiftUI - WWDC20" //
init(fileWrapper: FileWrapper, contentType: UTType) throws {
let data = fileWrapper.regularFileContents!
self = try JSONDecoder().decode(Self.self, from: data)
}
func write(to fileWrapper: inout FileWrapper, contentType: UTType) throws {
let data = try JSONEncoder().encode(self)
fileWrapper = FileWrapper(regularFileWithContents: data)
}
//
}
//// Rest of data model ////
Public struct CellRow : Hashable, Codable, Identifiable {
public var id: Int
var CellsOfRow: [ContentCell] = [ContentCell(), ContentCell(), ContentCell()] // < Array could be left empty.
}
struct ContentCell { // < A class probably wouldn't work with fileDocument, from what I've heard.
var isMarkedOff: Bool = false
var cellText: String = ""
}
Any help would be greatly appreciated.