First of all, i am very sorry for the noob question, but i just cant seem to figure this out.
I am very new to coding and just started to get my feet wet with SwiftUI, following a few courses and started to dabble in trying to create some basic apps.
I am currently working on an app that does an API call and displays the data.
My issue is, im trying to put the decoded data into an array, it sounds so simple and I think i am missing something very easy, but for the life of me I cant seem to figure it out.
Below is the codable struct I have
struct Drinks: Codable, Identifiable {
let id = UUID()
let strDrink : String
let strInstructions: String
let strDrinkThumb: String?
let strIngredient1: String?
let strIngredient2: String?
let strIngredient3: String?
let strIngredient4: String?
let strIngredient5: String?
}
I want to put the ingredients into an Array so I can go through them in lists etc
import SwiftUI
struct IngredientView: View {
let drink : Drinks
let ingredientArray : [String] = [] // I want to append the ingredients here
var body: some View {
GroupBox() {
DisclosureGroup("Drink Ingredience") {
ForEach(0..<3) { item in
Divider().padding(.vertical, 2)
HStack {
Group {
// To use the array here
}
.font(Font.system(.body).bold())
Spacer(minLength: 25)
}
}
}
}
}
}
Again, sorry for the noob question that probably has a simple answer, but worth a shot asking 😀
Thanks!
3
Answers
change you struct to
wherever you want to loop through ingredients you can use
drink.strIngredients
arrayyou could use this approach to get all your ingredients into an array and use
it in Lists. The idea is to use a function to gather all your ingredients into an array of
Ingredient
objects. You could also use a computed property.It is best to use a
Ingredient
object and declare itIdentifiable
so that when you use them in list and ForEach, each one will be
unique, even if the names are the same.
First of all your design cannot work because you are ignoring the root object, a struct with a key
drinks
A possible solution is to write a custom
init
method. However this a bit tricky because you have to inject dynamicCodingKeys
to be able to decode the ingredients in a loopFirst create a custom
CodingKey
structIn the
Drink
struct – by the way it’s supposed to be named in singular form – specify a second container, create the ingredient keys on the fly, decode the ingredients in a loop and append the results to an array until the value isnil
. Somebody should tell the owners of the service that their JSON structure is very amateurish. As you have to specify theCodingKeys
anyway I mapped the keys to more meaningful and less redundant struct member names.In the view display the ingredients like this