SwiftUI - фильтр JSON и сопоставление с базовыми данными - PullRequest
0 голосов
/ 28 февраля 2020

Я новичок в Swift & SwiftUI, поэтому, возможно, у меня есть простое решение моей проблемы.

Я пытаюсь сопоставить файл JSON с основными данными. Поэтому, если в рецепте появляется слово «Помидор» (Core Data), оно должно показывать кДж (JSON).

Я уже пробовал несколько вещей, но я все больше и больше путаюсь .

Спасибо!

Мой код:

[
{
   "id": 135
  ,"food":"Tomato"
  ,"kcal": 19
  ,"kJ": 79
  ,"be": 0
  ,"kh": 2.7
  ,"fett": 0.2
  ,"ew": 1.2
},
]
import Foundation

struct FoodList: Codable, Identifiable {
    var id: Int
    var food: String
    var kcal: Double
    var kJ: Double
    var be: Double
    var kh: Double
    var fett: Double
    var ew: Double
}
import Foundation

extension Bundle {
    func decode<T: Decodable>(_ type: T.Type, from file: String, dateDecodingStrategy: JSONDecoder.DateDecodingStrategy = .deferredToDate, keyDecodingStrategy: JSONDecoder.KeyDecodingStrategy = .useDefaultKeys) -> T {
        guard let url = self.url(forResource: file, withExtension: nil) else {
            fatalError("Failed to locate \(file) in bundle.")
        }

        guard let data = try? Data(contentsOf: url) else {
            fatalError("Failed to load \(file) from bundle.")
        }

        let decoder = JSONDecoder()
        decoder.dateDecodingStrategy = dateDecodingStrategy
        decoder.keyDecodingStrategy = keyDecodingStrategy

        do {
            return try decoder.decode(T.self, from: data)
        } catch DecodingError.keyNotFound(let key, let context) {
            fatalError("Failed to decode \(file) from bundle due to missing key '\(key.stringValue)' not found – \(context.debugDescription)")
        } catch DecodingError.typeMismatch(_, let context) {
            fatalError("Failed to decode \(file) from bundle due to type mismatch – \(context.debugDescription)")
        } catch DecodingError.valueNotFound(let type, let context) {
            fatalError("Failed to decode \(file) from bundle due to missing \(type) value – \(context.debugDescription)")
        } catch DecodingError.dataCorrupted(_) {
            fatalError("Failed to decode \(file) from bundle because it appears to be invalid JSON")
        } catch {
            fatalError("Failed to decode \(file) from bundle: \(error.localizedDescription)")
        }
    }
}
import CoreData
import SwiftUI

struct DetailView: View {
    let recipe: Recipe

    var foodList = Bundle.main.decode([FoodList].self, from: "FoodList.json")

    var body: some View {
        ScrollView {
            VStack {
                Text("\(self.recipe.ingredient1 ?? "")")

// Here I want to check if foodlist.food == recipe.ingredient1
// and return Text ("\(foodlist.kcal)")

            }
        }
    }
}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...