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')
Thank you for your help
[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).