The compiler is unable to type-check this expression in reasonable time in Xcode 12 with SwiftUI

I've just begun running into this error and I've seen that a few others have had this problem as well but there never seems to be a general solution.

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

I know my code isn't necessarily optimized per se but I don't think this should be happening

Code Block swift
var body: some View {
        return NavigationView {
            List {
                ForEach(tasks, id: \.dueDate) {
                    TaskRow(task: $0)
                }.onDelete(perform: deleteTask)
                Section(header: Text("Projects")
                            .font(.title2)
                            .fontWeight(.bold)
                            .foregroundColor(Color.pink)) {
                    ForEach(projects, id: \.projectTitle) {
                        ProjectRow(project: $0)
                    }.onDelete(perform: deleteProject)
                }
            }.toolbar {
                ToolbarItem (placement: .primaryAction) {
                    #if os(iOS)
EditButton()
.padding(10)
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(10)     
            #endif
                }
                ToolbarItem (placement: .bottomBar) {
                    Button(action:
                        self.isAddingTask = true
                        self.isAddingProject = false
                        self.isPresenting = true
                    }) {
                        Text("Add Task")
                            .fontWeight(.semibold)
                   }.padding(10)
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(10)
                }
                ToolbarItem (placement: .bottomBar) {
                    Button(action: {
                        self.isAddingTask = false
                        self.isAddingProject = true
                        self.isPresenting = true
                    }) {
                        Text("Add Project")
                            .fontWeight(.semibold)
                  }.padding(10)
.background(Color.pink)
.foregroundColor(.white)
.cornerRadius(10)
                }
            }
            .sheet(isPresented: $isPresenting) {
                if isAddingProject {
                    AddProject() { projectTitle in
                        self.addProject(projectTitle: projectTitle)
                        resetModal()
                    }
                } else if isAddingTask {
                    AddTask() { taskDescription, dueDate in
                        self.addTask(taskDescription: taskDescription, dueDate: dueDate)
                        resetModal()
                    }
                }
            }
            .navigationBarTitle(Text("Tasky"))
        }


The error says it's happening at the Navigation View but I have a sneaking suspicion Xcode doesn't actually know.

Post not yet marked as solved Up vote post of mshipman Down vote post of mshipman
34k views

Replies

In my experience of getting the same error, I take it as

There is some type-related issue around here

The actual issue might be
  • The expression is actually too complex for Swift compiler

  • You have some type-related errors inside the expression

To eliminate the second case, you need to check
  • All the syntax is really valid? For example, your line 30 lacks the opening brace {.

  • All the properties used there are really declared and have the right types and annotations?

  • All the methods used there are really declared and have the right signatures?

  • All the views used there are really declared as valid View?

When I copied your code into a new project and filled missing parts by guess, it compiled fine.

Then I removed :View from the struct AddProject, Swift compiler showed The compiler is unable to type-check this expression....

I hope Swift Team will fix this behavior soon, but until then you need to go over this hard-to-find-where message.
Try commenting out each subpart one by one, and find what really is causing the issue.
The way that I've gotten around this is by commenting out sections of the view or, in your case, the toolbar. I would build the project a few times so that every section is built at least once. After commenting and correcting any errors that was with the first section that was built, uncomment one of the commented sections and comment the uncommented section and build. Once you've done this for each section, you should be able to uncomment everything and it should succeed in building. This is only a workaround, however. See my example view below:

First Build:
Code Block swift
struct Example: View {
var body: some View {
List {
Section {
EmptyView()
}
//Section {
// EmptyView()
//}
//Section {
// EmptyView()
//}
//Section {
// EmptyView()
//}
}
}


Second Build:
Code Block swift
struct Example: View {
var body: some View {
List {
//Section {
// EmptyView()
// }
Section {
EmptyView()
}
//Section {
// EmptyView()
//}
//Section {
// EmptyView()
//}
}
}


And so on until you've built all of your sections. After this you should be able to uncomment everything and it should be able to build everything.
  • Well this worked, thanks

  • It saves me a lot of time. Thanks

Add a Comment
@OOer, So I've done more troubleshooting, the missing { on line 30 is there in my version, must've accidentally deleted it. I think I've narrowed the issue down to the AddTask() view used in line 65 (thank you @thafner). What I'm trying to do is create a Core Data relationship which I've set up in my data model and now want to expose to users so that they can add tasks to an overarching project. The AddTask view works fine until I attempt to even display current tasks in a list, I haven't begun making those changes to the data store because listing them doesn't seem to work and still throws the The compiler is unable to type-check... error in the same place. I've included the contents of AddTask below:

Code Block swift
public struct AddTask: View {
    static let DefaultTaskDescription = "Something productive"
    static let DefaultDueDate = Date()
    @State var taskDescription: String = ""
    @State var dueDate: Date = Date()
    let onComplete: (String, Date) -> Void
    @State private var selectedProject: Project = Project()
    @FetchRequest(
      entity: Project.entity(),
      sortDescriptors: [
        NSSortDescriptor(keyPath: \Project.projectTitle, ascending: true)
      ]
    ) var projects: FetchedResults<Project>
    public var body: some View {
        NavigationView {
            Form {
                Section(header: Text("Task Description")) {
                  TextField("Task", text: $taskDescription)
                }
                Section(header: Text("Due Date")) {
                    DatePicker("Select a due date", selection: $dueDate, in: Date()..., displayedComponents: .date).labelsHidden()
                }
                HStack {
                    Spacer()
                    Button(action: addMoveAction) {
                        Text("Add Task").fontWeight(.bold)
                                        .padding(10)
                                        .foregroundColor(.white
                                        .background(Color.blue)
                                        .cornerRadius(10)
                    }
                    Spacer()
                }
            }
            .navigationBarTitle(Text("Create Task"), displayMode: .inline)
            List {
              ForEach(projects, id: \.self) { project in
                    project.projectTitle.map(Text.init).font(Font.body.bold())
            }
        }
    }
  private func addMoveAction() {
    onComplete(
        taskDescription.isEmpty ? AddTask.DefaultTaskDescription : taskDescription,
        dueDate == Date() ? AddTask.DefaultDueDate : dueDate
    )
  }
}

I'm not sure why trying to display the projects like it's done in ContentView is causing this issue
Again, your code has some errors.
  • Line 34 lacks closing parenthesis )

  • Between 45 and 46, another closing brace } is needed

  • Line 45 causes error, isn't it Text(project.projectTitle).font(Font.body.bold())?

And fixing all such errors, I cannot reproduce The compiler is unable to type-check....
The causes of the unable to type-check may be mutually dependent, so there may be other issues in other parts of your code.
Seems that xcode has trouble lint/type checking inside closures. I was building the below view and made some typos, then my macbook started overheating due to xcode and could not get proper lint errors.

Code Block
struct ContentView: View {
  let astronauts: [Astronaut] = Bundle.main.decode("astronauts.json")
  let missions: [Mission] = Bundle.main.decode("missions.json")
  var body: some View {
    NavigationView {
      List(missions) { mission in
        NavigationLink(
          destination: Text("Detail View"),
          label: {
            Image(mission.image)
              .resizable()
              .scaledToFit()
              .methodThatDoesntExit()
              .frame(width: 44, height: 44)
            VStack(alignment: .leading) {
              Text(mission.displayName)
                .font(.headline)
              Text(mission.formattedLaunchDate)
            }
          })
      }
      .navigationTitle("Moonshot")
    }
  }
}


This will will throw a generic error instead of telling me .methodThatDoesntExit() doesn't exist.

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

One solution is to create a separate item view and provide that in the closure, then everything works as expected.


The fact that this times out and doesn't give any feedback really limits my ability to adopt SwiftUI. Apple needs to fix this, because I have perfectly valid Swift UI code that mysteriously blows up the compiler. I don't know at which point in my expansion of a VC that I'll run into this (I've run into this one three different occasions now) so I'm at the point of freezing any deeper adoption of SwiftUI. Looking forward to a new version of XCode that addresses that in some fashion so I can unblock my SwiftUI adoption.
For example I'm working on an audio app that may have more than a dozen audio effects, once I get more than 11 of these effect ScrollViews going in a List{} then the compiler goes out to lunch...
if (flangerFxEnabled) {
        let efxFlangerParmNum = efxFlanger.count
        ScrollView(.horizontal) {
          HStack(spacing: 20) {
            Text("Flanger:").font(.system(size: 10.0))
            ForEach(0..<efxFlangerParmNum) {
              Text(efxFlanger[$0].name)
                .font(.system(size: 8.0))
                .frame(width: 60, height: 40)
              Slider(value: self.$delegate.efxFlanger[$0].value, in: efxFlanger[$0].lowRange...efxFlanger[$0].hiRange, step: 0.1).frame(width: 100, height: 40)
               
            }
          }
        }
      }

      if (chorusFxEnabled) {
        let efxChorusParmNum = efxChorus.count
        ScrollView(.horizontal) {
          HStack(spacing: 20) {
            Text("Chorus:").font(.system(size: 10.0))
            ForEach(0..<efxChorusParmNum) {
              Text(efxChorus[$0].name)
                .font(.system(size: 8.0))
                .frame(width: 60, height: 40)
              Slider(value: self.$delegate.efxChorus[$0].value, in: efxChorus[$0].lowRange...efxChorus[$0].hiRange, step: 0.1).frame(width: 100, height: 40)
               
            }
          }
        }
      }

etc... up to 12 & then boom...
I'm getting this too trying to implement a UIViewControllerRepresentable wrapping around image picker. I had my own class / struct for that initially, but figured I messed something up, so I went and snagged a couple of examples from the 'net with the same results.

I'm running Xcode 12.4 on Bit Sur 11.2.1 on an M1 mini.

I thought I'd do this latest project in SwiftUI, but once again, I'm just feeling like it's not ready for prime time, and this is a show stopper for me; I'm ready to trash it and start over in .XIBs because I've done this same thing 100 times in .XIBs and storyboard with 100% no issues.

I even stripped out all the view controller stuff in my ControllerReprestable and just went with a wrapping of a very generic UIViewController.


I've got the same error message and it really point me to nowhere but fogs.
I've start my projects on SWIFU UI and there are a lot of codes in it but now I can't move on since my projects won't compile and I am not sure why...
this is very counter-productive, hence frustrating.

I'm getting the same with the following code for a simple calculator app:

struct ContentView: View {
  //Local variables and constants
  @State var operatorChain: [String] = []
  @State var oprandChain: [Double] = []
  @State var operand: Double = 0.0
  @State var resultText: String = ""
  @State var numericalResult: Double = 0.0
  let defaultText: String = "0"
   
  var body: some View {
    ZStack {
      Color
        .black
        .ignoresSafeArea(.all)
      VStack {
//---------------------------------------------------------------------------------
        //Result display START
        Spacer()
        HStack{
          Spacer()
          if resultText == "" {
            Text(defaultText)
              .foregroundColor(.white)
              .font(.system(size: 100))
          }
          else if resultText.count <= 6 {
            Text(resultText)
              .foregroundColor(.white)
              .font(.system(size: 100))
          }
          else if resultText.count > 6 && resultText.count < 13 {
            Text(resultText)
              .foregroundColor(.white)
              .font(.system(size: 50))
          }
        }
        .padding()
        //Result display END
//---------------------------------------------------------------------------------
        //Button display START
        //Row 1
        HStack {
          Spacer()
          Button(action: {
            resultText = defaultText//left off here
             
          }) {
            makeCalcButtonText(buttonText: CalcButton.clear)
          }
          .buttonStyle(CalcButtonStyle())
          Spacer()
          Button(action: {
            operatorChain.append(CalcButton.negative.rawValue)
          }) {
            makeCalcButtonText(buttonText: CalcButton.negative)
          }
          .buttonStyle(CalcButtonStyle())
          Spacer()
          Button(action: {
            operatorChain.append(CalcButton.percent.rawValue)
          }) {
            makeCalcButtonText(buttonText: CalcButton.percent)
          }
          .buttonStyle(CalcButtonStyle())
          Spacer()
          Button(action: {}) {//pick up here
            makeCalcButtonText(buttonText: CalcButton.divide)
          }
          .buttonStyle(CalcButtonStyle())
          Spacer()
        }
        .padding()
        //Row 2
        HStack {
          Spacer()
          Button(action: {
             
          }) {
            makeCalcButtonText(buttonText: CalcButton.seven)
          }
          .buttonStyle(CalcButtonStyle())
          Spacer()
          Button(action: {
             
          }) {//pick up here
            makeCalcButtonText(buttonText: CalcButton.eight)
          }
          .buttonStyle(CalcButtonStyle())
          Spacer()
          Button(action: {
             
          }) {//pick up here
            makeCalcButtonText(buttonText: CalcButton.nine)
          }
          .buttonStyle(CalcButtonStyle())
          Spacer()
          Button(action: {}) {//pick up here
            makeCalcButtonText(buttonText: CalcButton.multiply)
          }
          .buttonStyle(CalcButtonStyle())
          Spacer()
        }
        .padding()
        //Row 3
        HStack {
          Spacer()
          Button(action: {
             
          }) {
            makeCalcButtonText(buttonText: CalcButton.four)
          }
          .buttonStyle(CalcButtonStyle())
          Spacer()
          Button(action: {
             
          }) {
            makeCalcButtonText(buttonText: CalcButton.five)
          }
          .buttonStyle(CalcButtonStyle())
          Spacer()
          Button(action: {
             
          }) {
            makeCalcButtonText(buttonText: CalcButton.six)
          }
          .buttonStyle(CalcButtonStyle())
          Spacer()
          Button(action: {}) {//pick up here
            makeCalcButtonText(buttonText: CalcButton.subtract)
          }
          .buttonStyle(CalcButtonStyle())
          Spacer()
        }
        .padding()
        //Row 4
        HStack {
          Spacer()
          Button(action: {
             
          }) {
            makeCalcButtonText(buttonText: CalcButton.one)
          }
          .buttonStyle(CalcButtonStyle())
          Spacer()
          Button(action: {
             
          }) {
            makeCalcButtonText(buttonText: CalcButton.two)
          }
          .buttonStyle(CalcButtonStyle())
          Spacer()
          Button(action: {
             
          }) {
            makeCalcButtonText(buttonText: CalcButton.three)
          }
          .buttonStyle(CalcButtonStyle())
          Spacer()
          Button(action: {}) {//pick up here
            makeCalcButtonText(buttonText: CalcButton.add)
          }
          .buttonStyle(CalcButtonStyle())
        }
        .padding()
        //Row 5
        HStack {//error is present here
          Spacer()
          Button(action: {}) {//pick up here
            makeCalcButtonText(buttonText: CalcButton.zero)
          }
          .buttonStyle(CalcButtonStyle())
          Spacer()
          Button(action: {}) {//pick up here
            makeCalcButtonText(buttonText: CalcButton.decimal)
          }
          .buttonStyle(CalcButtonStyle())
          Spacer()
          Button(action: {}) {//pick up here
            makeCalcButtonText(buttonText: CalcButton.equal)
          }
          .buttonStyle(CalcButtonStyle())
          Spacer()
        }
        .padding()
        Spacer()
      }
    }
  }
}

After a while, I decided to move the computations into another swift file and leave the ContentView.swift file for the visual part. If I remove the following code:

@State var operatorChain: [String] = []
@State var oprandChain: [Double] = []

I will get the same exact error message. It is pretty counter productive, I'm just learning swift so that I can develop for current technologies in the market and I'm stuck with that. However, I may just leave them there for now, though they may or not be used.

I got this error from Xcode when attempting to compile this rather simple floating point constant:

Float((1.0 / 255.0) * 0.5 - (1.0e-7 * (1.0 / 255.0) * 0.5))

It's a clipping constant for 8 bit per pixel image data in the floating point space.

I am getting the same compiler error using Xcode 13.2.1. The offending line of code is the NavigationLink, located at the bottom of the following, minimal reproducible sample. If I comment out that one line, the error goes away and the compile is almost instantaneous.

Any suggestions? I've already tried using Strings instead of Ints for the tag/selection parameters. Same error.


import SwiftUI
import Foundation

enum MarkerType: Double {
  case unlabeled = -99
  case end = -4
  case start = -3
  case stop = -2
  case blank = -1
  case image = 1
}

class LabeledImage {
  let image: Image
  let marker: Double
  var appeared = false
   
  init(image: Image, marker: Double) {
    self.image = image
    self.marker = marker
  }
}

struct SlideShow {
  private let maxImages: Int = 10000
  var images = [LabeledImage]()
  var labels = [String]()
  var totalImages: Int { return self.images.count }
  private var fromFolder: URL
   
  init(fromURL: URL = Bundle.main.bundleURL.appendingPathComponent("Contents/Resources/DefaultImages")) {
    self.fromFolder = fromURL
  }
}

class AppState: ObservableObject {
  static var docDir: URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
  @Published var isMainMenuActive = false
  @Published var loadFolder: URL = Bundle.main.bundleURL.appendingPathComponent("Contents/Resources/DefaultImages")
  @Published var intervalSeconds: Double = 0.6

  var saveFolder = URL(fileURLWithPath: "BCILab", relativeTo: docDir)
  var labels = [String]()
  var totalImages: Int = 0
  var saveIndex: Int = 0
}


struct minsample: View {
  @StateObject private var appState = AppState()
  @State private var slideshow = SlideShow()
  @State private var selection: Int = 0
   
  private func insertAppears(_ marker: Double) {
    let nmarker = marker + 100.0
  }
   
  var body: some View {
    NavigationView {
      ForEach(0..<slideshow.images.count-1, id: \.self) { i in
        let thisImage = slideshow.images[i].image
          .resizable()
          .aspectRatio(contentMode: .fit)
          .onAppear(perform: { insertAppears(slideshow.images[i].marker) })
        let nextImage = slideshow.images[i+1].image
          .resizable()
          .aspectRatio(contentMode: .fit)
          .onAppear(perform: { insertAppears(slideshow.images[i+1].marker) })

        NavigationLink(destination: nextImage, tag: i, selection: self.$selection) { thisImage }
      }
    }
  }
}

To break up the expression into distinct sub-expressions, you can try separating out each part of the calculation into its own intermediate variable. Here is one example.way you could do this:

internal static let EaseOutBack = { (elapsed: TimeInterval, duration: TimeInterval) -> Double in let s: TimeInterval = 1.70158 var position: TimeInterval = elapsed / duration position -= 1.0 let a = position * position let b = (s + 1.0) * position let c = a * (b + s) let result = c + 1.0 return Double(result) }

This still seems to be an issue. Using Xcode 14.2 (14C18) on Ventura 13.2.1 (22D68) on an arm64 Macbook, I run into the same issues with some fairly simple stuff. The code below builds very fast. If I just make changes in this particular file and rebuild with the rest of the project cached, it takes about a second from build to launch. However, just adding one statement and the compiler would end up with The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions after using almost all available CPU power for about a minute.

Here comes the code:

struct ModelGroupDetailsView: View {
    @Binding var modelGroup: modelGroup
    
    private static let bottomPadding: CGFloat = 10
    private static let insetNormal: CGFloat = 15
    private static let insetDeep: CGFloat = 18

    var body: some View {
        List {
            ForEach($modelGroup.objects) { $object in
                Section {
                    VStack(alignment: .leading, spacing: 0) {
                        if object.childObjects.count == 0 {
                            Text("This object does not contain any childObjects.")
                                .padding(.leading, Self.insetNormal)
                                .padding(.bottom, Self.bottomPadding)
                        }
                        ForEach(object.childObjects) { childObject in
                            Label(childObject.url.lastPathComponent, systemImage: "externaldrive")
                                .foregroundColor(Color.black.opacity(0.6))
                                .padding(.leading, Self.insetNormal)
                                .padding(.bottom, Self.bottomPadding / 2)
                                .padding(.top, Self.bottomPadding / 2)
                            
                            let grandChildObjects = childObject.grandChildObjects
                            if grandChildObjects.count == 0 {
                                Text("This childObject does not contain any grandChildObjects.")
                                    .padding(.leading, Self.insetDeep)
                                    .padding(.bottom, Self.bottomPadding)
                                    .font(Font.system(size: 11))
                            } else {
                                Table(of: GrandChildObject.self) {
                                    TableColumn("ID") { Text($0.id.description) }
                                    TableColumn("Tag") { Text($0.tag) }
                                    TableColumn("Creation date") { Text($0.creationDate.formatted()) }
                                } rows: {
                                    ForEach(grandChildObjects) { TableRow($0) }
                                }
                                .frame(height: CGFloat(grandChildObjects.count) * 28 + 26)
                                .padding(.bottom, Self.bottomPadding)
                                .scrollDisabled(true)
                            }
                            if object.childObjects.last != childObject {
                                if object.childObjects.last?.grandChildObjects.count ?? 0 > 0 {
                                    Divider()
                                        .padding(.bottom, Self.bottomPadding + 4)
                                } else {
                                    Divider()
                                        .padding(.leading, Self.insetDeep)
                                        .padding(.bottom, Self.bottomPadding + 4)
                                }
                            }
                        }
                        if modelGroup.objects.last != object {
                            Divider()
                                .padding(.leading, Self.insetNormal)
                                .padding(.bottom, Self.bottomPadding)
                        }
                    }
                } header: {
                    HStack {
                        Button(action: removeObject(object)) {
                            Label("Remove object", systemImage: "trash")
                                .labelStyle(.iconOnly)
                        }
                        .padding(6)
                        .buttonStyle(RemoveButtonStyle())
                        Text(object.url.lastPathComponent)
                            .font(Font.system(size: 13, weight: Font.Weight.medium))
                            .foregroundColor(Color.black)
                            .frame(maxWidth: .infinity, alignment: .leading)
                        
                    }
                }
            }
        }
        .id(self.modelGroup)
        .toolbar {
            ToolbarItemGroup(placement: .principal) {
                Button(action: addObject) {
                    Label("Create new object", systemImage: "plus")
                }
                .help("Add more objects")
                
                Spacer(minLength: 10)
                
                Button(action: popSnapshot) {
                    Label("Remove latest grandchild", systemImage: "rectangle.stack.badge.minus")
                }
                .help("Remove the latest grandchild for all childObjects in modelGroup")
                Button(action: pushSnapshot) {
                    Label("Create new grandchild", systemImage: "rectangle.stack.badge.plus")
                }
                .help("Create a new grandchild for all childObjects in modelGroup")
            }
        }
        .navigationTitle(modelGroup.name)
    }
    ...
}

I just had exactly the same error after just modifying two lines of code. By undoing the changes I found out the problem was the use of the TextField modifier .textInputAutocapitalization(). In fact it is working fine with .autocapitalization() instead, though marked as deprecated.