Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SwiftUI: why can't I map views in a previews in PreviewProvider?

I know that I can display several previews doing this:

struct TestView: View {
    let number: Int
    
    var body: some View {
        ZStack {
            Color.orange
            Text("\(number)")
                .fontWeight(.heavy)
                .font(.system(size: 56.0))
        }
        .frame(width: 100, height: 100, alignment: .center)
    }
}

struct TestView_Previews: PreviewProvider {
    static var previews: some View {
        TestView(number: 3)
        TestView(number: 5)
    }
}

But why can’t I, instead, write this instead?

static var previews: some View {
    [3, 5].map { TestView(number: $0) }
}

(I’m getting this error: Return type of static property ‘previews’ requires that ‘[TestView]’ conform to ‘View’)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thank you for your help

>Solution :

[TestView], also known as Array<TestView>, does not conform to View.

SwiftUI’s solution is the ForEach view:

static var previews: some View {
    ForEach([3, 5], id: \.self) {
        TestView(number: $0)
    }
}

Note that this assumes every element of the array is unique (which is true in this example).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading