skip to Main Content

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


  1. Chosen as BEST ANSWER

    Update: I was able to figure it out. The following code appears to work:

    struct RecipeItemDetailView_Previews: PreviewProvider {
    static var previews: some View {
        RecipeItemDetailView(recipeDetails: .constant([StoredRecipeModel].init()))
    }
    

  2. 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 a Binding type of [StoredRecipeModel], an array of your custom type StoreRecipeModel.

    struct StoredRecipeModel {
           var name: String
    }
    RecipeItemDetailView(recipeDetails: .constant([StoredRecipeModel(name: "Food")]))
    

    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.

    Login or Signup to reply.
  3. 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:

    • Binding .constant values are hard-coded so they cannot be
      changed.
    • It is always read-only and that’s how the .constant
      works.
    • Once you have a real-data, you can replace .constant and pass a
      regular Binding value.
    • It supports all Swift Datatypes
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search