Вы можете использовать протокол Codable для кодирования и декодирования ваших классов в файл JSON, но я рекомендую использовать структуры:
struct Entry: Codable {
let company, category, type: String
let amount: Double
}
struct CheckBook: Codable {
var entries: [Entry] = []
}
extension FileManager {
static let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
}
Тестирование игровой площадки:
let checkBooks: [CheckBook] = [.init(entries: [.init(company: "ACME", category: "JSON", type: "Swift", amount: 5.0)])]
do {
let destinationURL = FileManager.documentDirectory.appendingPathComponent("CheckBooks.json")
try JSONEncoder().encode(checkBooks).write(to: destinationURL)
print("json encoded/saved")
let loadedCheckBooks = try JSONDecoder().decode([CheckBook].self, from: .init(contentsOf: destinationURL))
print(loadedCheckBooks) // CheckBook(entries: [Entry(company: "ACME", category: "JSON", type: "Swift", amount: 5.0)])\n"
} catch {
print(error)
}