0

Thanks to some help here I got this mostly working, but I'm not sure what the correct syntax is for how I can get SwiftUI's PreviewProvider to display the contents of my array "myDataModels".

Here is what I have:

import SwiftUI

struct Overview: View {
    var myDataModels: [MyDataModel]

    var body: some View {
        List {
            ForEach(myDataModels) { model in
                Section(header: Text("\(model.firstName) \(model.lastName)")) {

                    ForEach(model.cities, id: \.name) { (city: City) in

                        Section(header: Text(city.name).fontWeight(.bold)) {

                            ForEach(city.towns, id: \.name) { town in
                                Text(town.name)
                            }
                        }
                    }
                }
            }
        }
    }
}

Which compiles fine, but I'm not sure what the correct means of referencing myDataModels is for the PreviewProvider call just below the above block. Here is what I have there currently.

struct Overview_Previews: PreviewProvider {
    static var previews: some View {
        Overview(myDataModels: userData[0])
    }
}

userData is a reference to the JSON file. But I get the error:

Cannot convert value of type 'MyDataModel' to expected argument type '[MyDataModel]'

Any help us most appreciated.

2
  • 1
    What happens if you pass userData instead of userData[0] in your preview provider? Commented Oct 28, 2019 at 19:55
  • 2
    The error message was telling you what was wrong, you were passing a single object while your component was expecting an array. Commented Oct 28, 2019 at 20:05

1 Answer 1

0

Assuming you've defined userData somewhere, you can just do

Overview(myDataModels: userData)

Or if you want to just send the one specific item:

Overview(myDataModels: [userData[0]])

If this doesn't work, please post your definition of userData.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.