I cannot seem to figure out how to initialize a @Binding that is of type Array:
struct RecipeItemDetailView: View {
@Binding var recipeDetails: [StoredRecipeModel]
var body: some View {
NavigationView {
VStack {
Text(recipeDetails[1].name)
}
}
}
struct RecipeItemDetailView_Previews: PreviewProvider {
static var previews: some View {
RecipeItemDetailView(recipeDetails: <#Binding<[StoredRecipeModel]>#>)
}
In the above, you will see that in the PreviewProvider after "recipeDetails: " it is asking that I initialize recipeDetails. I put the sample code in that is is asking for. I am able to initialize less complex bindings (e.g. .constant(false) ) but that does not work in this case.
Any thoughts?
Hopefully I am using the correct terms here, as I am quite new to programming!
3
Answers
Update: I was able to figure it out. The following code appears to work:
The SwiftUI
Binding
type includes a method called.constant()
. You claim that.constant()
does not work in this case, but it is actually possible to create a dummy binding data of any type.Solution
You need to initialize a new instance of
StoredRecipeModel
, and pass it as a parameter into.constant()
. The following code snippet compiles with no problem, because it creates aBinding
type of[StoredRecipeModel]
, an array of your custom typeStoreRecipeModel
.Your updated answer does compile without error, but it is an empty list initialized. I doubt that’s what you want because it will not show anything on screen.
First of all, Bindings are used when we want to share values in different places and the shared variables will be connected and receive updates at the same time when the values get changed. Now in this case, if we want to prototype a user interface by passing a Binding value, but we don’t have actual variable to bind, we can use .constant, which acts as a Binding variable for previews.
Important points:
changed.
works.
regular Binding value.