Если я удалю переменную options
, код будет работать, но мне это нужно. Я думаю, что проблема в том, что массив опций может / может быть пустым.
Модель
struct Schedule: Codable {
let batch: String
let menu: SubSchedule?
}
struct SubSchedule: Codable {
let name: String
let price: Int
let options: [Options]? // <--- If I remove this, it'll work
}
struct Options: Codable {
let field: String?
let options: [SubOption]?
}
struct SubOption: Codable {
let _id: String
let addPrice: Int
let value: String
}
Сервис
URLSession.shared.dataTask(with: url) { data, _, _ in
let result = try? JSONSerialization.jsonObject(with: data!, options: [])
print(result as Any) // print decoded json
let schedules = try!
JSONDecoder().decode([Schedule].self, from: data!)
DispatchQueue.main.sync {
completion(schedules)
}
}.resume()
JSON
{
"batch": "Lunch",
"menu": {
"name": "Dailysuki Tomyam Soup",
"options": [{
"field": "Tambah Nasi",
"options": [{
"addPrice": 0,
"value": "None"
}]
}],
// options not always have a value (may empty)
//
// options: ['']
//
"price": 25000
}
}
ОШИБКА
Fatal error: 'try!' expression unexpectedly raised an error: Swift.DecodingError.typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "menu", intValue: nil), CodingKeys(stringValue: "options", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "Expected to decode Dictionary<String, Any> but found a string/data instead.", underlyingError: nil)): file /PROJECT/Services/Webservices.swift, line 23