"the compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions" ...... it killing me !!!!
I don’t work on the compiler, so my knowledge of this is based on ‘listening in’ on conversations on Swift Forums. If you want definitive answers, I recommend that you search those forums for this topic; it’s been discussed many times.
However, I do want to address this:
I REALLY hope the engineers at Apple will fix this though!
While this situation has improved, and you can expect it to improve further in the future, it doesn’t make sense to think of this as a straightforward bug that can be fixed. This error in intrinsic to the Swift language.
Swift has lots of flexibility: type inference, untyped literals, function overloading, operator overloading, and more. That flexibility makes type checking difficult. The compiler uses a constraint solver to find the best types for a specific statement, and the nature of the input constraints means that, in some situations, finding a solution, or proving that there’s no solution!, requires exponential time. That’s the root cause of this failure.
Swift’s implementation of this works pretty well in most cases, but sometimes things run off the rails. I most commonly see this crop up in two cases:
-
In correct code that uses a lot of literals and operator overloading.
-
In incorrect code, where an error is the code causes the compiler to head off into the weeds.
The error’s advice, to break “the expression into distinct sub-expressions”, works well in the first case. And there are other things you can do in that case as well. For example, you can add type annotations, which reduces the space that the constraint solver needs to search.
The second case is more annoying because a small tweak to working code can result in a hard-to-identify error. Claude31 posted some good suggestions here. I have a few more (-:
SwiftUI works best with small views. That helps with this problem, but it’s good practice regardless. It allows you to develop, preview, and test your views in isolation.
SwiftUI works best when your views just contain view code. I see a lot of SwiftUI projects with ‘model level’ code in the views. That’s problematic in general, but it also opens the door to to this error. If you’re starting a URLSession
task from a view, you should rethink your design.
Adding type annotations can help here as well. I’ve found it particularly helpful to add types to closures. By specifying the closure’s inputs and outputs, you limit the scope of type inference.
If you have specific examples of this error, please do post them here. We, as a community, are still learning this stuff, and I love discussing concrete problems.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"