I have found examples online that use hardcoded uuids in the json file and the works perfectly for me, however as I am adding the ability to delete items from the json array in my app I need these uuid's to be created dynamically
Here is my json file (list.json), it used to have hard coded ids like "id": 1 and worked (when I used int for ids )
[
{
"name": "Dune",
"author": "Frank Herbert",
"page": "77"
},
{
"name": "Ready Player One",
"author": "Ernest Cline",
"page": "234"
},
{
"name": "Murder on the Orient Express",
"author": "Agatha Christie",
"page": "133"
}
]
Here is my struct (Book.swift)
struct Book: Hashable, Codable, Identifiable {
var id = UUID()
var name: String
var author: String
var page: String
}
When I decode my json file using this struct with the code (Data.swift)...
let bookData: [Book] = load("list.json")
func load<T: Decodable>(_ filename: String) -> T {
let data: Data
guard let file = Bundle.main.url(forResource: filename, withExtension: nil)
else {
fatalError("Couldn't find \(filename) in main bundle.")
}
do {
data = try Data(contentsOf: file)
} catch {
fatalError("Couldn't load \(filename) from main bundle:\n\(error)")
}
do {
let decoder = JSONDecoder()
return try decoder.decode(T.self, from: data)
} catch {
fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)")
}
}
my last fatal error is executed because the id key has no value associated with it (because I removed it in my json file)
How do I initialize my json file with an id so that my id = UUID()
statement in my struct can assign it a unique id?
Okay so here is my solution. Rather than dynamically filling the id field now, I will fill them when I am using an Encodable function with variable = UUID().uuidstring. Therefore my examples will have hardcoded ids but when people add their own books to my app, my app will generate the id. Its a simple solution but as a beginner I didn't know what to look for.