I would like to create a Swift TableView for all available sizes of coffee within a specific type. With this JSON tree, how can you structure the class to create an array for the type specific sizes?
The JSON Tree is structured as follows:
{
"_id": "60ba1ab72e35f2d9c786c610",
"types": [
{
"_id": "60ba1a062e35f2d9c786c56d",
"name": "Ristretto",
"sizes": [
"60ba18d13ca8c43196b5f606",
"60ba3368c45ecee5d77a016b"
],
"extras": [
"60ba197c2e35f2d9c786c525"
]
},
{
"_id": "60be1db3c45ecee5d77ad890",
"name": "Espresso",
"sizes": [
"60ba3368c45ecee5d77a016b",
"60ba33dbc45ecee5d77a01f8"
],
"extras": [
"60ba34a0c45ecee5d77a0263"
]
},
{
"_id": "60be1eabc45ecee5d77ad960",
"name": "Cappuccino",
"sizes": [
"60ba18d13ca8c43196b5f606",
"60ba3368c45ecee5d77a016b",
"60ba33dbc45ecee5d77a01f8"
],
"extras": [
"60ba197c2e35f2d9c786c525",
"60ba34a0c45ecee5d77a0263"
]
}
],
"sizes": [
{
"_id": "60ba18d13ca8c43196b5f606",
"name": "Large",
"__v": 0
},
{
"_id": "60ba3368c45ecee5d77a016b",
"name": "Venti"
},
{
"_id": "60ba33dbc45ecee5d77a01f8",
"name": "Tall"
}
],
"extras": [
{
"_id": "60ba197c2e35f2d9c786c525",
"name": "Select the amount of sugar",
"subselections": [
{
"_id": "60ba194dfdd5e192e14eaa75",
"name": "A lot"
},
{
"_id": "60ba195407e1dc8a4e33b5e5",
"name": "Normal"
}
]
},
{
"_id": "60ba34a0c45ecee5d77a0263",
"name": "Select type of milk",
"subselections": [
{
"_id": "611a1adeff35e4db9df19667",
"name": "Soy"
},
{
"_id": "60ba348d8c75424ac5ed259e",
"name": "Oat"
},
{
"_id": "60ba349a869d7a04642b41f4",
"name": "Cow"
}
]
}
]
}
My classes: (I can currently load a TableView with the coffee sizes, but not the type specific sizes)
import Foundation
import UIKit
class Types: Codable {
let types: [CoffeeType]
init(types: [CoffeeType]) {
self.types = types
}
}
class Sizes: Codable {
let sizes: [CoffeeType]
init(sizes: [CoffeeType]) {
self.sizes = sizes
}
}
class CoffeeType: Codable {
let _id: String
let name: String
init(_id: String, name: String) {
self._id = _id
self.name = name
}
}
The app is structured like this: HomeViewController is a TableView of Types. When you click on a Type, you transition to SelectSizeViewController, to which I have already assigned a Type through the segue. On SelectSizeViewController, I would like to display the list of specific sizes.
CodePudding user response:
use QuickType to get the model this is quite helpful. you will be getting the model easily(suggestion). I think you are using the wrong model.
if your Base model struct is correct it should be something like this
struct Coffie: Codable {
let id: String
let types: [TypeElement]
let sizes: [Size]
let extras: [Extra]
enum CodingKeys: String, CodingKey {
case id
case types, sizes, extras
}
}
from here itself you can get the type and sizes with corresponded id's you can filter size values from sizes array