Creating Multiple Bodies

Hello there! Recently I ran into an issue with the var body: some View part of the view, where it had so much code it couldn't type-check fast enough. I was told to divide it into multiple smaller bodies, but I cannot figure out how to do that. Let me share an example of some code:
Code Block swift
struct ContentView: View {
let exampleVariable = "Example"
func exampleFunc {
print("Example")
}
var body: some View {
Text("Hello")
}
var secondBody: some View {
Text("World")
}
}
struct ContentView_Previews: PreviewProvider {
  static var previews: some View {
    Group {
      ContentView()
        .previewDisplayName("iPod Touch")
         
    }
       
       
  }
}
// I cannot figure out what to do to this last part that actually makes the view include the second body, "secondBody"

If anyone knows how to fix this, I'd love to hear from you! Any help is appreciated!
Accepted Answer
Is it what you are looking for ?

Code Block
struct ContentView: View {
let exampleVariable = "Example"
func exampleFunc() {
print("Example")
}
var body: some View {
Text("Hello")
secondBody
}
var secondBody: some View {
Text("World")
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
Group {
ContentView()
.previewDisplayName("iPod Touch")
}
}
}

Yes! Thank you! The errors Xcode sent were just adding strange parameters that got errored anyway. Now it is working!
Actually, I have one more question. I am trying to make it so the secondBody only shows up when it is within a range of a value. Something like this within the first body parameter:

Code Block
if stepNum > 4 {
      secondBody
    }


This does work, but I end up with two views crammed into one screen like I added a VStack. Is there any way to remove the first body?
You need to hide it.

I found a useful extension here:
https://stackoverflow.com/questions/56490250/dynamically-hiding-view-in-swiftui

If you prefer, could write another extension with isVisible ; but usual API is for hiding.

Now, your code becomes:

Code Block
extension View {
/// Hide or show the view based on a boolean value.
@ViewBuilder func isHidden(_ hidden: Bool, remove: Bool = false) -> some View {
if hidden {
if !remove {
self.hidden()
}
} else {
self
}
}
}
struct ContentView: View {
let exampleVariable = "Example"
func exampleFunc() {
print("Example")
}
var body: some View {
Text("Hello")
secondBody
.isHidden(stepNum <= 4) // Condition to hide is opposite to condition to show
}
var secondBody: some View {
Text("World")
}
}


Creating Multiple Bodies
 
 
Q