1
votes

I'm trying to build a ForEach()-Loop in SwiftUI for building UI-Elements, but I'm getting this error-message:

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

Here is my code:

    var body: some View {
        HStack {
            HStack {
                VStack {
                    ForEach((1...10).reversed(), id: \.self) {
                        Text("\($0)")
                        Spacer()
                    }
                    Spacer()
                }
                Spacer()
            }
            Spacer()
        }
    }

The Error is pointing on the Line with the ForEach-Statement. I tried to follow the tutorial by Paul Hudson, see: https://www.hackingwithswift.com/quick-start/swiftui/how-to-create-views-in-a-loop-using-foreach

1

1 Answers

1
votes

In short: remove Spacer() from ForEach. ForEach expects to return one value of type some View. You could wrap your Text() and Spacer() into HStack or VStack, but in this case you couldn't access the each number in your array via closure syntax ($0 notation should be changed to { element in } ). So the next code would work:

var body: some View {
    HStack {
        HStack {
            VStack {
                ForEach((1...10).reversed(), id: \.self) { number in
                    HStack {
                        Text("\(number)")
                        Spacer()
                    }
                }
                Spacer()
            }
            Spacer()
        }
        Spacer()
    }
}