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?
In this case you have to specify
CodingKeysand omitidApparently the struct members are not going to be modified so declare them as constants.