Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI - Ternary operator on padding modifier crashes program

I've got a ZStack in SwiftUI filled with some components delivered by a ForEach, as follows:

ForEach(0..<arr.count) { i in
  ZStack {
    ...
  }

  // I use i later in this code
  ...
}

The program runs perfectly like this.

But I want to add padding to the ZStack only if i == 0, so I tried adding this modifier to the ZStack: .padding(.top, i == 0 ? 70 : 0)

When I try to build it with this modifier it fails, but doesn't even say "build failed." It takes about 5 minutes attempting to build (when it usually takes 5 seconds) then decides to crash. Can anyone explain why this is happening and how I can get this conditional padding without breaking my program?

like image 855
Nicolas Gimelli Avatar asked Jun 18 '26 21:06

Nicolas Gimelli


1 Answers

Try this:

ForEach(0..<arr.count) { i in
  ZStack {
    ...
  }
  .padding(.top, getPadding(i))

  // I use i later in this code
  ...
}
func getPadding(_ i: Int) -> CGFloat {
        if i == 0 {
                return CGFloat(70)
        }
            
        return CGFloat(0)
}
like image 130
fballjeff Avatar answered Jun 22 '26 07:06

fballjeff