Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add ID Property on Struct Fetched From JSON

I have a ‘Recipe’ struct whose instances are created by parsing a JSON file. All the properties of Recipe map to the JSON, except for one: id.

I want each struct instance to be uniquely identifiable via this property, and it should be generated whenever the struct is instantiated, however, when instances of struct are created, all of their ids are nil.

Recipe.swift

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import Foundation

struct Recipe: Identifiable, Decodable {
    var id = UUID()
    let name:String
    let featured:Bool
    let image:String
    let description:String
    let prepTime:String
    let cookTime:String
    let totalTime:String
    let servings:Int
    let ingredients:[String]
    let directions:[String]
}

RecipeMode.swift (instances of Recipe struct)

import Foundation
import SwiftUI

class RecipeModel {
    var recipes = loadRecipes()
}

func loadRecipes() -> [Recipe] {
    var recipes = [Recipe]()
    let fileURL = URL(fileURLWithPath: Bundle.main.path(forResource: "recipes", ofType: "json")!)
    do {
        let data = try Data(contentsOf: fileURL)
        recipes = try JSONDecoder().decode([Recipe].self, from: data)
    } catch {
        print(error)
    }
    return recipes
}

>Solution :

use let id = UUID() instead of var id = UUID(), and the id will not be decoded.

If the Xcode warning scare you too much, you can also use this:

struct Recipe: Identifiable, Decodable {
    var id = UUID()
    let name:String
    let featured:Bool
    let image:String
    let description:String
    let prepTime:String
    let cookTime:String
    let totalTime:String
    let servings:Int
    let ingredients:[String]
    let directions:[String]
    
    // not including id
    enum CodingKeys: String, CodingKey {
        case name, featured, image, description, prepTime, cookTime
        case totalTime, servings, ingredients, directions
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading