Search code examples
swiftuipaddingmodifier

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?


Solution

  • 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)
    }