UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

HStack based on enum array, type check error?

Forums > SwiftUI

Hi all, just playing around with a WWDC 19 Avacado Toast type app, I am having trouble getting an array of emums for toppings into a HStack. This code works (with 2 toppings, see below), but when I add a third (if else for .avocado) I get the error "The compiler is unable to type-check this expression in reasonable time"

struct Order: Identifiable {
    var id = UUID()
    var name: String
    var toppings: [Toppings]
}

enum Toppings {
    case cheese
    case tomato
    case avocado
    case ham
}
struct OrderCellView: View {
    var order: Order
    var body: some View {
        HStack {
            Text("TEXT")
            Spacer().modifier(HSpacerModifier())
            ForEach(order.toppings, id: \.self) { topping in
                Group {
                    if topping == .cheese {
                        Cheese()
                    } else if topping == .tomato {
                        Tomato()
                    }
                }
            }
        }
    }
}

Gary

2      

I got this working by using a function to return the appropriate view as AnyView, any other methods would be most welcome.

struct OrderCellView: View {
    var order: Order
    var body: some View {
        HStack {
            Text("ORDER")
            Spacer().modifier(HSpacerModifier())
            ForEach(order.toppings, id: \.self) { topping in
                self.toppingView(topping: topping)
            }
        }
    }

    func toppingView(topping: Toppings) -> AnyView {
        switch topping {
        case .cheese: return AnyView(Cheese())
        case .tomato: return AnyView(Tomato())
        case .avocado: return AnyView(Avocado())
        case .ham: return AnyView(Ham())
        }
    }
}

Pic

2      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.