Posts

Post marked as solved
8 Replies
4.8k Views
I'm using SwiftUI to create my app, and I want to use "if" statement to conditionally add a View to a VStack, but the following code fails to compile in my project:struct BookItemGroupVertical: View { // BudgetBook is a custom class var items: [BudgetBook] private var halfNumber: Int { return Int(items.count / 2) } var body: some View { VStack(alignment: .leading) { ForEach(0 ..< self.halfNumber) { index in // BookItemGroupHorizontal is a custom View BookItemGroupHorizontal(items: [self.items[index * 2], self.items[index * 2 + 1]]) } // This is where the problem happens if items.count % 2 == 1 { Text("it") } } } }However, I've tried a simpler sample and it works:struct ConditionalTestView: View { var array = [1, 2, 3, 4, 5] var body: some View { VStack { ForEach(0 ..< 5) { _ in Text("Something") } if array.count % 2 == 1 { Text("Second Line") } } } }I'm wondering whether this is a bug of SwiftUI. If not, how can I solve this problem?Thanks.
Posted
by Andy_Luo.
Last updated
.