Nathan
Nathan

Reputation: 125

If statement inside ForEach causing Swift to Compile Error

I'm running into a very weird error with Swift and XCode right now. I have a very basic view containing a fetcher which returns an array of strings. I won't write out that part of the code because that code is not the issue, as I've been using the fetcher for multiple builds now without issue. The probably is, I want to format the string differently depending on what its value is. Before adding this functionality in, it was building just fine with the code below;

ForEach(self.fetcher.fetched?.returnData ?? []) { result in
    VStack(alignment: .leading) {
        Text(result.text)
    }.frame(width: metrics.size.width * 1.0)
}

But somehow, when I try to modify this code into what is below, it throws the ambiguous error:

This expression cannot be type-checked in a reasonable amount of time 

around the entire stack which the ForEach is nested in. I have no clue why this is throwing this error, as the IF is written correctly.

ForEach(self.fetcher.fetched?.returnData ?? []) { result in
    if(result.text == "OtherSide") {
        VStack(alignment: .leading) {
            Text(result.text)
        }.frame(width: metrics.size.width * 1.0)
    } else {
        VStack(alignment: .trailing) {
            Text(result.text)
        }.frame(width: metrics.size.width * 1.0)
    }
}

Any help would be appreciated, kind of hard to progress because I'm stuck at this road block and can't figure out what's going on.

Upvotes: 1

Views: 1372

Answers (2)

テッド
テッド

Reputation: 906

A potential solution is to put the conditional statements into a Group as in the following example:

struct TestView: View {

@State var array = [1,2,3,4,5]

var body: some View {
    ScrollView {
        ForEach(array, id: \.self) { num in
            Group {
            if num % 2 == 0 {
                Text("Even")
            } else {
                Text("Odd")
            }
            }
        }
    }
}

}

Upvotes: 1

Asperi
Asperi

Reputation: 258057

In this case it can be solved with not much changes as conditional branches are almost the same

ForEach(self.fetcher.fetched?.returnData ?? []) { result in
    VStack(alignment: result.text == "OtherSide" ? .leading : .trailing) {
       Text(result.text)
    }.frame(width: metrics.size.width * 1.0)
}

More common rule for such compiler error (by experience) is to decompose view builder into smaller parts, ie. function generating sub view, computable property for subview, or separating some part into completely new view struct.

Upvotes: 3

Related Questions