1
votes

I am using Xcode 11.3.1 with SwiftUI.

This code works right

struct ContentView: View {
    var body: some View {
        VStack {
            ForEach(1...5, id: \.self) { index in
                Text("\(index) of coffee.")
            }
        }
    }
}

enter image description here But the following code gives an error.

why?

struct ContentView: View {
    var body: some View {
        VStack {
            ForEach(1...5, id: \.self) { index in
                if index == 1 {
                    Text("Cup of coffee.")
                } else {
                    Text("\(index) cups of coffee")
                }
            }
        }
    }
}

The error message is:

Unable to infer complex closure return type; add explicit type to disambiguate.

1

1 Answers

1
votes

Because view builder expected one return of one type view, but condition does not generate opaque return. To solve - just embed condition in Group

ForEach(1...5, id: \.self) { index in
  Group {
    if index == 1 {
        Text("Cup of coffee.")
    } else {
        Text("\(index) cups of coffee")
    }
  }
}