Codable
will only work if ALL the elements are codable. In the Regatta
class you have, Skipper
,ScoreMethod
and BoatClass
. You have given the Skipper
class and see that it is Codable
, however the other two (which is assume are enum
s) these also need to confrom to Codable
If you remove them you will see that the code should work!
struct Regatta: Identifiable, Codable {
var id = UUID()
var name: String
// var scoreType: ScoreMethod = .Lowpoint
var startDate: Date
var endDate: Date
var contact: String
// var boatClass: BoatClass = .DF95
var skippers: [Skipper]
}
class RegattaList: ObservableObject {
@Published var regattas: [Regatta]
let savePath = FileManager.documentsDirectory.appendingPathExtension("SavedRegattas")
init() {
do {
let data = try Data(contentsOf: savePath)
regattas = try JSONDecoder().decode([Regatta].self, from: data)
} catch {
regattas = []
// why doesnt this work?
//regattas = [Regatta(name: "Getting Started", scoreType: ScoreMethod.Lowpoint, startDate: Date(), endDate: Date(), contact: "You!")]
}
}
private func save() {
do {
let data = try JSONEncoder().encode(regattas)
try data.write(to: savePath, options: [.atomic, .completeFileProtection])
} catch {
print("Unable to save data.")
}
}
func add(_ regatta: Regatta) {
regattas.append(regatta)
save()
}
let dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .short
//formatter.timeStyle = .medium
return formatter
}()
}
struct Skipper: Codable {
var id: UUID
var firstName: String
var lastName: String
var boatNum: Int
var sailNum: Int
static func ==(lhs: Skipper, rhs: Skipper) -> Bool {
return lhs.lastName == rhs.lastName && lhs.sailNum == rhs.sailNum
}
}
extension FileManager {
static var documentsDirectory: URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return paths[0]
}
}
struct ContentView: View {
@StateObject private var regattaList = RegattaList()
var body: some View {
List {
ForEach(regattaList.regattas) { regatta in
Text(regatta.name)
}
}
}
}