import Foundation
extension Bundle {
func decode(_ file: String) -> [Menu] {
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()
do {
return try decoder.decode([Menu].self, from: data)
} catch DecodingError.keyNotFound(let key, let context) {
fatalError("Failed to decode \(file) from bundle due to missing key '\(key.stringValue)' – \(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)")
}
}
}
Но я получаю следующую ошибку: «Не удалось декодировать Menu.json из пакета из-за несоответствия типов. Ожидалось декодирование Array, но вместо этого был обнаружен словарь».
Правильно ли я моделирую данные? Или это проблема с функцией декодирования в пакете?
Я пытался изменить способ моделирования данных, но я новичок в JSON, поэтому не совсем уверен, проблема в том, как я смоделировал JSON в Swift.
struct Menu : Codable, Hashable { var id: UUID { UUID() } let day: String let locationName: String let coordinate: [Double] let menu: OrderedDictionary
} [/code] А вот как я расшифровываю данные: [code]import Foundation
extension Bundle { func decode(_ file: String) -> [Menu] { 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()
do { return try decoder.decode([Menu].self, from: data) } catch DecodingError.keyNotFound(let key, let context) { fatalError("Failed to decode \(file) from bundle due to missing key '\(key.stringValue)' – \(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)") } } } [/code] Но я получаю следующую ошибку: «Не удалось декодировать Menu.json из пакета из-за несоответствия типов. Ожидалось декодирование Array, но вместо этого был обнаружен словарь». Правильно ли я моделирую данные? Или это проблема с функцией декодирования в пакете? Я пытался изменить способ моделирования данных, но я новичок в JSON, поэтому не совсем уверен, проблема в том, как я смоделировал JSON в Swift.