How to set a var inside a View definition

I am really tring to understand why I can't put any code that just changes a var inside of the var body = some View section. I can test vars and do stuff but I need to change a var / @State inside and as soon as I add that line I get error "Unable to infer complex closure return type; add explicit type to disambiguate". I have really simplified this down (bogus code for example, real code is looping through an array list. When the one line "lastSection = '1234'" is added, that causes the code. I think this is because a view is only expecting a "View" Type like Text, Image, List, etc and doesn't know what to do with the code. How else are you supposed to actually set / change anything dynamically in a View section?


struct FetchView: View {

@State var lastSection = ""


var body: some View {

NavigationView {

VStack {

Text("1234")

if lastSection != "1234" {

Text("A")

lastSection = "1234"

}

}.navigationBarTitle(Text("Site Listing"))

}

}

}

}

Replies

VStack must only have views.


What do you expect in your code ?


In fact, you cannot change the state without some event that triggers the change.

The following will work

struct FetchView1: View {
    @State var lastSection = "X"
   
    var body: some View {
        NavigationView {
            VStack {
                Text("1234 \(lastSection)")
                if lastSection != "1234" {
                    Text("A")
                    Button(action: {self.lastSection = "1234"}) {
                    Text("Change section")
                    }
                    //                         lastSection = "1234"
                }
            }.navigationBarTitle(Text("Site Listing"))
        }
    }
}


I also tested the following:


struct SubView: View {
    @Binding var lastSection : String

    var body: some View {
        if lastSection != "1234" {
            self.lastSection = "1234"
            return Text("A")
        }
        return Text("B")
    }
}

struct FetchView: View {
    @State var lastSection = ""
   
    var body: some View {
        NavigationView {
            VStack {
                SubView(lastSection: $lastSection)
                Text("1234")
            }.navigationBarTitle(Text("Site Listing"))
        }
    }
}