Swift’s use of type inference makes our code shorter and easier to read, but it also chews up a lot of CPU time. Sometimes a value could be one of several types, and if it gets used with another things that could be one of several types then the amount of work Swift has to do multiplies. If Swift encounters something with so many possibilities that it simply can’t figure it out after about 15 seconds, it throws an error instead: “Expression was too complex to be solved in reasonable time; consider breaking up the expression into distinct sub-expressions.”
This is something the Swift team are working to improve with every new version of Swift, and there’s no real fixed cut-off for when the compiler will throw this error. However, at the time of writing Swift 4.2 is the latest available version and you can cause the error with code as simple as this:
let a = 0 let sum = abs(a + a) + abs(a + a) + abs(a + a)
The combination of operator overloading and function overloading means that code is simple but certainly isn’t easy – at least not for Swift.
Fortunately, this error message tells you exactly what you need to do to fix the problem: break up the expression into multiple subexpressions. That is, calculate independent parts individually, then combine them together. The trivial example from above would become this:
let a = 0 let part1 = abs(a + a) let part2 = abs(a + a) let part3 = abs(a + a) let sum = part1 + part2 + part3
Available from iOS 8.0
Did this solution work for you? Please pass it on!
Other people are reading…
About the Swift Knowledge Base
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.
Test your Swift today
Think you know Swift? My book Swift Coding Challenges will put your Swift skills to the test – it's perfect for job interviews and more!