I'm trying to get used to the MVVM-Pattern in swift. So I was coding around a bit and I get this error again and again:
The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions
I read a lot here, and i know that breaking up the code in smaller peaces would help - but with SwiftUI, I mean, thats pretty difficult, cause the code I wrote is just how it should be using SwiftUI (correct me if I'm wrong).
So, I'm pretty frustrated right now, trying to get this to work. Maybe anybody has an idea?
Here is a screenshot:
And the code:
import SwiftUI
struct ContentView: View {
var modelPizza = PizzaModel()
var body: some View {
NavigationView {
List(modelPizza.pizzas) { p in
NavigationLink(
destination:
Text("Destination"),
label: {
VStack(alignment: .leading) {
Text(p.name)
.font(.title)
HStack {
Text(p.toping1)
.italic()
Text(p.toping2)
.italic()
Text(p.toping3)
.italic()
}
}
})
}.navigationTitle("Pizzas")
Button(action: {
print("Hello")
}, label:
Text("Hello")
)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Would love to hear from you - Thanks in advance.
Make sure your Pizza struct conforms to Identifiable if you want to write it this way; otherwise, use List(modelPizza.pizzas, id: \.self)
and have Pizza conform to Hashable.
I suggest adding a UUID property to pizza to conform to Identifiable. The code below is an example that works on Swift 5, Xcode version 12.3:
struct ContentView: View {
var modelPizza = PizzaModel()
var body: some View {
NavigationView {
List(modelPizza.pizzas) { pizza in
NavigationLink(destination: Text("Destination")) {
VStack(alignment: .leading) {
Text(pizza.name)
.font(.title)
HStack {
Text(pizza.topping1)
.italic()
Text(pizza.topping2)
.italic()
Text(pizza.topping3)
.italic()
}
}
}
}
}
}
struct PizzaModel {
var pizzas = [Pizza]()
struct Pizza: Identifiable {
var id = UUID()
var name: String
var topping1: String
var topping2: String
var topping3: String
}
}
}
Alternatively:
struct PizzaModel {
var pizzas = [Pizza]()
struct Pizza: Hashable {
var name: String
var topping1: String
var topping2: String
var topping3: String
}
}
and use List(modelPizza.pizzas, id: \.self)
.