Home > Enterprise >  How can I break up my code so Xcode will let my run my App | SwiftUI
How can I break up my code so Xcode will let my run my App | SwiftUI

Time:01-04

I get this error

The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions

The code why the error happens is like this:

ForEach(items){ item in
                    var abgektItem = abgehakt.first(where: {i in i.id == item.id})
                    var normalItem = abgektItem.normalItem
                    var normalItemAnzahl = normalItemAnzahl ?? 0
                    var anzhal = item.normalItem!.Anzahl - normalItemAnzahl
                    someView(anzhal)
                }.padding(.vertical)

I simplified the code. How can I break up the code even more? I mean I mead for every single step a new variable...

Thanks for your help, Boothosh

CodePudding user response:

This often means you have a bug, not that the expression is actually too complex. For example, these lines are incorrect:

var abgektItem = abgehakt.first(where: {i in i.id == item.id})
var normalItem = abgektItem.normalItem

first(where:) returns an Optional, so abgektItem.normalItem is not valid. Sometimes determining that incorrect code is definitely incorrect (i.e. that there is no way that with type promotion or coercion or some protocol extension that it could be made to work) is combinatorially explosive, which is what leads to this message rather than a proper error.

Generally the best way to debug this (and for more readable code generally) is to move the computation to a function:

ForEach(items) { item in computeView(item) }

where computeView is a local function along the lines of:

func computeView(_ item: Item) -> some View {
    // compute
    return someView(anzhal)
}

If you move this code to a new computeView function, the compiler will almost certainly find your bug quickly.

CodePudding user response:

i already have this message, its when you put too much logic in your view, do the check etc in your viewModel and it will be fine

  •  Tags:  
  • Related