swiftjsondecoderswift-structs

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

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 {
        let 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
        }
    }