1

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

0

1 Answer 1

3

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()
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

That solved my problem, thank you. I'm just kicking into SwiftUI and some errors are weird.

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.