在从 JSON 获取的结构上添加 ID 属性

Add ID Property on Struct Fetched From JSON

我有一个 'Recipe' 结构,其实例是通过解析 JSON 文件创建的。 Recipe 的所有属性映射到 JSON,除了一个:id.

我希望每个结构实例都可以通过这个 属性 唯一标识,并且应该在实例化结构时生成它,但是,当创建结构实例时,它们的所有实例 id s 是 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(配方结构的实例)

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
}

使用let id = UUID()代替var id = UUID()id不会被解码。

如果Xcode警告吓到你了,你也可以用这个:

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